UNPKG

patronum

Version:

☄️ Effector utility library delivering modularity and convenience

97 lines (95 loc) 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.throttle = throttle; var _effector = require("effector"); function throttle(...args) { const argsShape = args.length === 2 ? { source: args[0], timeout: args[1] } : args[0]; const { source, timeout, target = (0, _effector.createEvent)({ name: "target", sid: "-gyhb56" }) } = argsShape; if (!_effector.is.unit(source)) throw new TypeError('source must be unit from effector'); const $timeout = toStoreNumber(timeout); const timerFx = (0, _effector.createEffect)({ name: `throttle(${source.shortName || source.kind}) effect`, handler: timeout => new Promise(resolve => setTimeout(resolve, timeout)) }, { name: "timerFx", sid: "-lp5bot" }); // It's ok - nothing will ever start unless source is triggered const $payload = (0, _effector.createStore)(null, { and: { serialize: 'ignore', skipVoid: false }, name: "$payload", sid: "w71tnu" }).on(source, (_, payload) => payload); const triggerTick = (0, _effector.createEvent)({ name: "triggerTick", sid: "-dquigt" }); const $canTick = (0, _effector.createStore)(true, { and: { serialize: 'ignore' }, name: "$canTick", sid: "e2dxhp" }).on(triggerTick, () => false).on(target, () => true); (0, _effector.sample)({ and: [{ clock: source, filter: $canTick, target: triggerTick }], or: { sid: "-hifwv4" } }); (0, _effector.sample)({ and: [{ source: $timeout, clock: triggerTick, target: timerFx }], or: { sid: "-h3lgud" } }); (0, _effector.sample)({ and: [{ source: $payload, clock: timerFx.done, target }], or: { sid: "-h0apa7" } }); return target; } function toStoreNumber(value) { if (_effector.is.store(value, { sid: "-gj92sk" })) return value; if (typeof value === 'number') { if (value < 0 || !Number.isFinite(value)) throw new Error(`timeout must be positive number or zero. Received: "${value}"`); return (0, _effector.createStore)(value, { and: { name: '$timeout' }, sid: "-2ktcsz" }); } throw new TypeError(`timeout parameter should be number or Store. "${typeof value}" was passed`); }