UNPKG

thaw

Version:

The narrow belt for AOP 🥋

75 lines (74 loc) • 1.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.throttle = exports.pipe = exports.debounce = exports.before = exports.around = exports.afterThrowing = exports.afterReturning = exports.after = void 0; const after = (fn, advice) => { return function (...args) { try { return fn.apply(this, args); } finally { advice.apply(this, args); } }; }; exports.after = after; const afterReturning = (fn, advice) => { return function (...args) { return advice.call(this, fn.apply(this, args), ...args); }; }; exports.afterReturning = afterReturning; const afterThrowing = (fn, advice) => { return function (...args) { try { return fn.apply(this, args); } catch (err) { advice.call(this, err, ...args); throw err; } }; }; exports.afterThrowing = afterThrowing; const around = (fn, advice) => { return function (...args) { const proceed = () => fn.apply(this, args); return advice.call(this, proceed, ...args); }; }; exports.around = around; const before = (fn, advice) => { return function (...args) { advice.apply(this, args); return fn.apply(this, args); }; }; exports.before = before; const debounce = (fn, wait = 0) => { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, wait); }; }; exports.debounce = debounce; const pipe = (...fns) => { if (fns.length === 0) { return (...args) => args.length <= 1 ? args.at(0) : args; } return function (...args) { return fns.reduce((acc, fn, idx) => idx ? fn.call(this, acc) : fn.apply(this, acc), args); }; }; exports.pipe = pipe; const throttle = (fn, wait = 0) => { let timer; return function (...args) { timer ||= (fn.apply(this, args), setTimeout(() => { timer = null; }, wait)); }; }; exports.throttle = throttle;