UNPKG

function-performer

Version:

Performer providing API for debounce, throttle and deduplication functions

110 lines (109 loc) 3.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _export(target, all) { for(var name in all)Object.defineProperty(target, name, { enumerable: true, get: all[name] }); } _export(exports, { Performer: function() { return Performer; }, default: function() { return _default; } }); const _fastdeepequal = /*#__PURE__*/ _interop_require_default(require("fast-deep-equal")); function _define_property(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class Performer { debounce(func, ...args) { let call = this._debounce.calls.get(func); if (call === undefined) { call = { timeout: null }; this._debounce.calls.set(func, call); } if (call.timeout !== null) { clearTimeout(call.timeout); call.timeout = null; } call.timeout = setTimeout(()=>{ this._debounce.calls.delete(func); func(...args); }, this._debounce.interval); } throttle(func, ...args) { if (!this._throttle.calls.has(func)) { func(...args); this._throttle.calls.add(func); setTimeout(()=>{ this._throttle.calls.delete(func); }, this._throttle.interval); } } deduplicate(func, ...args) { let calls = this._deduplication.calls.get(func); if (calls === undefined) { calls = this._deduplication.calls.set(func, []).get(func); } let call = calls?.find((item)=>(0, _fastdeepequal.default)(item.args, args)); const shouldDeduplicate = call !== undefined; if (call === undefined) { call = { timeout: null, args, count: 1 }; calls?.push(call); } else { call.count++; } if (call.timeout !== null && shouldDeduplicate) { clearTimeout(call.timeout); call.timeout = null; } call.timeout = setTimeout(()=>{ this._deduplication.calls.delete(func); func(call.count, ...args); }, this._deduplication.interval); } constructor(config){ _define_property(this, "_debounce", void 0); _define_property(this, "_throttle", void 0); _define_property(this, "_deduplication", void 0); this._debounce = { calls: new Map(), interval: config?.debounce?.interval ?? 0 }; this._throttle = { calls: new Set(), interval: config?.throttle?.interval ?? 0 }; this._deduplication = { calls: new Map(), interval: config?.deduplication?.interval ?? 0 }; } } const _default = Performer;