UNPKG

util-ex

Version:

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

44 lines (43 loc) 1.64 kB
/** * Creates an executable function with dynamic scope binding * * Unlike statically scoped functions, this rebinds scope variables on every execution, * allowing runtime updates to the execution environment. The function achieves this * through closure-delayed scope binding, regenerating the target function on each call. * * @example * // Basic usage * const scopedFunc = newScopedFunction( * 'add', * ['x'], * 'return x + y', * { y: 10 } // Initial scope * ); * scopedFunc(5); // Returns 15 * * // Dynamic scope update * const scope = { y: 20 }; * const updatableFunc = newScopedFunction('add', ['x'], 'return x + y', scope); * updatableFunc(5); // Returns 25 * scope.y = 100; * updatableFunc(5); // Returns 105 * * @param {string} name - Function name (for debugging and stack traces) * @param {string[]} argNames - Formal parameter names (array format) * @param {string} body - Function body code (as JavaScript string) * @param {Object} scope - Execution scope object (key-value pairs) * * @returns {Function} Executable function that: * - Accepts arguments defined in `argNames` * - Regenerates the function using current `scope` on each call * - Returns the execution result * * @see {@link newFunction} Underlying static-scope function generator * * @warning Performance note: Rebuilds function object on every call - * avoid in high-frequency scenarios * @note Scope dynamism: Always uses latest `scope` reference (pass-by-reference) * * @since 1.0.0 */ export function newScopedFunction(name: string, argNames: string[], body: string, scope: any): Function;