UNPKG

@toreda/time

Version:

Simple, small footprint library for common time operations and converting between units of time.

94 lines (93 loc) 3.12 kB
"use strict"; 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 id_1 = require("./group/id"); /** * @category Timers */ class TimerCallbackGroup { constructor(id) { this.id = typeof id === 'string' && id.length > 0 ? id : (0, id_1.timerCallbackGroupIdNext)(); this._once = []; this._always = []; } reset() { this._once.length = 0; this._always.length = 0; } onceCt() { return this._once.length; } alwaysCt() { return this._always.length; } on(kind, fn) { if (typeof fn !== 'function') { return false; } const list = kind === 'once' ? this._once : this._always; list.push(fn); return true; } once(fn) { return this.on('once', fn); } always(fn) { return this.on('always', fn); } remove(kind, fn) { const list = kind === 'once' ? this._once : this._always; const i = list.indexOf(fn); if (i === -1) { return false; } list.splice(i, 1); return true; } invoke(fn, duration) { return __awaiter(this, void 0, void 0, function* () { const value = typeof duration === 'number' ? duration : 0; try { fn(value); } catch (e) { if (e instanceof Error) { console.error(`Callback group invoke error: ${e.message}`); } } }); } executeAll(duration) { return __awaiter(this, void 0, void 0, function* () { yield this.executeOnce(duration); yield this.executeAlways(duration); }); } executeOnce(duration) { return __awaiter(this, void 0, void 0, function* () { for (let i = this._once.length - 1; i >= 0; i--) { const item = this._once[i]; yield this.invoke(item, duration); // Listener was one-time use. Remove it after invoking it. this._once.splice(i, 1); } }); } executeAlways(duration) { return __awaiter(this, void 0, void 0, function* () { for (const item of this._always) { yield this.invoke(item, duration); } }); } } exports.TimerCallbackGroup = TimerCallbackGroup;