@stnekroman/tstools
Version:
Set of handy tools for TypeScript development
74 lines (73 loc) • 2.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Functions = void 0;
var Functions;
(function (Functions) {
function noop(..._args) { }
Functions.noop = noop;
function identity(arg) {
return () => arg;
}
Functions.identity = identity;
function join(...functions) {
return (...args) => {
for (const func of functions) {
func(...args);
}
};
}
Functions.join = join;
function extractor(field) {
return (obj) => {
return obj[field];
};
}
Functions.extractor = extractor;
function pipe(firstFn, ...restFns) {
const piped = ((...args) => {
let result = firstFn(...args);
for (const fn of restFns) {
result = fn(result);
}
return result;
});
piped.pipe = (...nexts) => {
return Functions.pipe(piped, ...nexts);
};
return piped;
}
Functions.pipe = pipe;
function memo(func, cacheId = (args) => args.toString()) {
const cache = new Map();
const memoized = ((...args) => {
const cached = cacheId(args);
if (cache.has(cached)) {
return cache.get(cached);
}
else {
const result = func(...args);
cache.set(cached, result);
return result;
}
});
memoized.clear = () => {
cache.clear();
};
return memoized;
}
Functions.memo = memo;
function retry(func, count = 3, onError = Functions.noop) {
let lastError;
for (let i = 0; i < count; i++) {
try {
return func();
}
catch (e) {
lastError = e;
onError(e);
}
}
throw lastError;
}
Functions.retry = retry;
})(Functions || (exports.Functions = Functions = {}));