UNPKG

iif-ts

Version:

> 🧠 A tiny utility for conditional insertion into arrays and objects using the spread operator. Supports lazy evaluation.

49 lines • 1.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.iifArray = iifArray; exports.iifObject = iifObject; /** * Conditionally includes values in an array using the spread operator. Supports both eager and lazy * evaluation. * * @example * const items = [ * 'a', * ...iifArray(true, 'b', 'c'), // ['a', 'b', 'c'] * ] * * @example * const safe = [...iifArray(user?.enabled, () => getExpensiveValue())] * * @template T * @param condition - If true, the values are included in the result. * @param values - One or more values or lazy functions that return values. * @returns An array of evaluated values or an empty array. */ function iifArray(condition, ...values) { return condition ? values.map((v) => (typeof v === 'function' ? v() : v)) : []; } /** * Conditionally includes properties in an object using the spread operator. Supports both eager and * lazy evaluation. * * @example * const obj = { * id: 1, * ...iifObject(true, { role: 'admin' }), // { role: 'admin' } * } * * @example * const safe = { * ...iifObject(config?.enabled, () => ({ debug: true })), * } * * @template T * @param condition - If true, the object is returned. * @param value - An object or a lazy function that returns an object. * @returns A shallow object or an empty object. */ function iifObject(condition, value) { return condition ? (typeof value === 'function' ? value() : value) : {}; } //# sourceMappingURL=main.js.map