UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

60 lines (56 loc) 1.16 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * 将字符串转为函数 * @param {string} func 字符串 * @returns {Function} 字符串对应的函数 * * @example * * parseFunction('()=>console.log(1)') * * // ()=>console.log(1) */ function parseFunction(func) { if (typeof func !== 'string') return func; var data = ''; try { // eslint-disable-next-line no-new-func data = new Function('', "return ".concat(func))(); } catch (e) { console.error('解析失败', e); } return data; } /** * 记忆函数:缓存函数的运算结果 * @param {Function} fn 输入函数 * @returns {any} 函数计算结果 * * @example * function test(a) { * return a + 2 * } * * const cachedTest = cached(test) * * cachedTest(1) * * // => 3 * * cachedTest(1) * * // => 3 */ function cached(fn) { var cache = Object.create(null); return function cachedFn(str) { var key = String(str); var hit = cache[key]; if (hit !== undefined) return hit; cache[key] = fn(str); return cache[key]; }; } exports.cached = cached; exports.parseFunction = parseFunction;