UNPKG

validatees

Version:

✅ Validation library for ES6+ modules

72 lines (71 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VListener = void 0; class VListener { constructor() { this.arraySet = new Set(); } register(args) { args.forEach((arg) => { var _a, _b, _c, _d; const options = { condition: (_b = (_a = arg.options) === null || _a === void 0 ? void 0 : _a.condition) !== null && _b !== void 0 ? _b : true, strict: (_d = (_c = arg.options) === null || _c === void 0 ? void 0 : _c.strict) !== null && _d !== void 0 ? _d : false, }; if (arg.array && Array.isArray(arg.array)) { const callbackArray = []; if (arg.callback && typeof arg.callback === "function") { callbackArray.push(arg.callback); } else { callbackArray.push(...arg.callback); } listenToChangesInArray(arg.array, callbackArray, options); this.arraySet.add({ id: Math.floor(Math.random() * 10000), array: arg.array }); } else { throw new Error("Invalid arguments"); } }); } remove(args) { args.forEach((arg) => { if (!arg.array || false === Array.isArray(arg.array)) { throw new Error("Invalid arguments"); } this.arraySet.forEach((set) => { if (arg.array === set.array) { set.array.push = Array.prototype.push; this.arraySet.delete(set); } }); }); } getNrOfListeners() { return this.arraySet.size; } } exports.VListener = VListener; exports.default = VListener; const listenToChangesInArray = (arr, callbacks, options) => { let canPush = true; arr.push = function (...items) { canPush = true; const passed = items.filter((item) => { const cb = callbacks.every((f) => f(item)); if (cb === options.condition) { return true; } else { canPush = false; return false; } }); if ((false === options.strict || (true === options.strict && true === canPush)) && passed.length > 0) { return Array.prototype.push.apply(arr, passed); } else { return arr.length; } }; };