UNPKG

util-ex

Version:

Browser-friendly enhanced util fully compatible with standard node.js

58 lines (56 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._createFunction = _createFunction; exports.default = void 0; var _object = _interopRequireDefault(require("./is/type/object.js")); var _array = _interopRequireDefault(require("./is/type/array.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* * Usage: * var fn = _createFunction('function yourFuncName(arg1, arg2){log(arg1+arg2);}', {log:console.log}); * * _createFunction('function abc(){}'); * _createFunction('function abc(){}', {log:console.log}) * _createFunction('function abc(){}', ['log'], [console.log]) * * fn.toString() is : * "function yourFuncName(arg1, arg2) { * return log(arg1+arg2); * }" */ /** * Create a function using the given body and scope. * * @param {string} body - The body of the function to create. * @param {object|string[]} [scope] - The scope of the function, as an object with key/value pairs or an array of strings. * @param {Array=} values - The values to use for the scope, if scope is an array. * @returns {function} - The created function. * * @example * var fn = _createFunction('function yourFuncName(arg1, arg2){log(arg1+arg2);}', {log:console.log}); * fn(2,3); //print 5 */ function _createFunction(body, scope, values) { if (arguments.length === 1) { // eslint-disable-next-line no-new-func return Function(`return ${body}`)(); } else { if (!(0, _array.default)(scope) || !(0, _array.default)(values)) { if ((0, _object.default)(scope)) { const keys = Object.keys(scope); values = keys.map(k => { return scope[k]; }); scope = keys; } else { values = []; scope = []; } } // eslint-disable-next-line no-new-func return Function(scope, `return ${body}`).apply(null, values); } } var _default = exports.default = _createFunction;