UNPKG

@intuitionrobotics/ts-common

Version:
101 lines 3.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Module = void 0; const exceptions_1 = require("./exceptions"); const merge_tools_1 = require("../utils/merge-tools"); const Logger_1 = require("./logger/Logger"); const validator_1 = require("../validator/validator"); const date_time_tools_1 = require("../utils/date-time-tools"); class Module extends Logger_1.Logger { // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected constructor(name) { super(name); this.initiated = false; this.config = {}; this.timeoutMap = {}; this.runAsync = (label, toCall) => { setTimeout(() => { this.logDebug(`Running async: ${label}`); new Promise(toCall) .then(() => { this.logDebug(`Async call completed: ${label}`); }) .catch(reason => this.logError(`Async call error: ${label}`, reason)); }, 0); }; this.name = this.deduceName(name).replace("_Class", ""); } deduceName(name) { if (name) return name; const tempName = this.constructor["name"]; if (!tempName.endsWith("_Class")) throw new exceptions_1.BadImplementationException(`Module class MUST end with '_Class' e.g. MyModule_Class, check class named: ${tempName}`); return tempName; } // // possibly to add // public async debounceSync(handler: TimerHandler, key: string, ms = 0) { // _clearTimeout(this.timeoutMap[key]); // // await new Promise((resolve, reject) => { // this.timeoutMap[key] = setTimeout(async (..._args) => { // try { // await handler(..._args); // resolve(); // } catch (e) { // reject(e); // } // }, ms) as unknown as number; // }); // } debounce(handler, key, ms = 0) { const k = "debounce" + key; (0, date_time_tools_1._clearTimeout)(this.timeoutMap[k]); this.timeoutMap[k] = (0, date_time_tools_1._setTimeout)(handler, ms); } throttle(handler, key, ms = 0) { const k = "throttle" + key; if (this.timeoutMap[k]) return; this.timeoutMap[k] = (0, date_time_tools_1._setTimeout)(() => { handler(); delete this.timeoutMap[k]; }, ms); } throttleV2(handler, key, ms, force = false) { const k = "throttle_v2" + key; const now = (0, date_time_tools_1.currentTimeMillies)(); const timeoutMapElement = this.timeoutMap[k]; if (timeoutMapElement && now - timeoutMapElement <= ms && !force) return; handler(); this.timeoutMap[k] = (0, date_time_tools_1.currentTimeMillies)(); } setConfigValidator(validator) { this.configValidator = validator; } setDefaultConfig(config) { this.config = config; } getName() { return this.name; } setName(name) { this.name = name; } setConfig(config) { this.config = this.config ? (0, merge_tools_1.merge)(this.config, config || {}) : config; } setManager(manager) { this.manager = manager; } init() { // ignorance is bliss } validate() { if (this.configValidator) (0, validator_1.validate)(this.config, this.configValidator); } } exports.Module = Module; //# sourceMappingURL=module.js.map