UNPKG

@beenotung/tslib

Version:
46 lines (45 loc) 1.55 kB
"use strict"; /** * Created by beenotung on 12/26/16. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.id = void 0; exports.curry = curry; exports.autoCurry = autoCurry; const lang_1 = require("./lang"); /* reference : http://stackoverflow.com/questions/27996544/how-to-correctly-curry-a-function-in-javascript */ function curry(f) { const arity = f.length; const res = arity === 0 ? f : partial(f, arity, []); return res; } exports.id = curry((x) => x); /** internal func, use id() instead */ function autoCurry(f) { const res = typeof f === 'function' && f.length > 0 ? partial(f, f.length, []) : f; return res; } /** * if enough N param, * then take LAST N param, apply to f * -- also carry acc to f (as bottom of args stack), but should be ignored by f) * -- the functions wrapped by f might use the stacked (extra) args * if this args has extra params, * then apply them to the result of f * else take all param, wait for extra param * */ function partial(f, arity, acc) { const next = function partialNext() { const args = arguments; const m = args.length; if (m < arity) { return partial(f, arity - m, (0, lang_1.concatArgs)(acc, args, 0, m)); } const result = autoCurry(f.apply(null, (0, lang_1.concatArgs)(acc, args, 0, arity))); if (arity < m) { return autoCurry(result.apply(null, (0, lang_1.copyArray)(args, arity, m - arity))); } return result; }; return next; }