@toreda/time
Version:
Simple, small footprint library for common time operations and converting between units of time.
68 lines (67 loc) • 2.53 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimerCallbackGroup = void 0;
const strong_types_1 = require("@toreda/strong-types");
/**
* @category Timers
*/
class TimerCallbackGroup {
constructor(id) {
this.id = (0, strong_types_1.idMake)('timer', id);
this._once = (0, strong_types_1.arrayMake)([], []);
this._always = (0, strong_types_1.arrayMake)([], []);
}
reset() {
this._once.reset();
this._once([]);
this._always.reset();
this._always([]);
}
execute(duration) {
return __awaiter(this, void 0, void 0, function* () {
yield this.once(duration);
yield this.always(duration);
});
}
invoke(fn, duration) {
return __awaiter(this, void 0, void 0, function* () {
const value = typeof duration === 'number' ? duration : 0;
try {
yield fn(value);
}
catch (e) {
if (e instanceof Error) {
console.error(`Callback group invoke error: ${e.message}`);
}
}
});
}
once(duration) {
return __awaiter(this, void 0, void 0, function* () {
const items = this._once();
for (let i = items.length - 1; i >= 0; i--) {
const item = items[i];
yield this.invoke(item, duration);
// Listener was one-time use. Remove it after invoking it.
items.splice(i, 1);
}
});
}
always(duration) {
return __awaiter(this, void 0, void 0, function* () {
for (const item of this._always()) {
yield this.invoke(item, duration);
}
});
}
}
exports.TimerCallbackGroup = TimerCallbackGroup;