super-utils-plus
Version:
A superior alternative to Lodash with improved performance, TypeScript support, and developer experience
44 lines (43 loc) • 1.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.compact = compact;
exports.compactNil = compactNil;
const is_1 = require("../utils/is");
/**
* Creates an array with all falsy values removed.
* Falsy values are false, null, 0, "", undefined, and NaN.
*
* @param array - The array to compact
* @returns The new array of filtered values
*
* @example
* ```ts
* compact([0, 1, false, 2, '', 3, null, undefined, NaN]);
* // => [1, 2, 3]
* ```
*/
function compact(array) {
if (!array || !array.length) {
return [];
}
return array.filter(Boolean);
}
/**
* Creates an array with all null and undefined values removed.
* Unlike compact, this preserves other falsy values like 0, '', and false.
*
* @param array - The array to compact
* @returns The new array of filtered values
*
* @example
* ```ts
* compactNil([0, 1, false, 2, '', 3, null, undefined, NaN]);
* // => [0, 1, false, 2, '', 3, NaN]
* ```
*/
function compactNil(array) {
if (!array || !array.length) {
return [];
}
return array.filter(item => !(0, is_1.isNil)(item));
}