mathjs
Version:
Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with dif
65 lines (53 loc) • 2.37 kB
JavaScript
; // function utils
/**
* Memoize a given function by caching the computed result.
* The cache of a memoized function can be cleared by deleting the `cache`
* property of the function.
*
* @param {function} fn The function to be memoized.
* Must be a pure function.
* @param {function(args: Array)} [hasher] A custom hash builder.
* Is JSON.stringify by default.
* @return {function} Returns the memoized function
*/
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
exports.memoize = function (fn, hasher) {
return function memoize() {
if (_typeof(memoize.cache) !== 'object') {
memoize.cache = {};
}
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
var hash = hasher ? hasher(args) : JSON.stringify(args);
if (!(hash in memoize.cache)) {
memoize.cache[hash] = fn.apply(fn, args);
}
return memoize.cache[hash];
};
};
/**
* Find the maximum number of arguments expected by a typed function.
* @param {function} fn A typed function
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {}).reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
/**
* Call a typed function with the
* @param {function} fn A function or typed function
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.callWithRightArgumentCount = function (fn, args, argCount) {
return Object.keys(fn.signatures || {}).reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};