@wezom/toolkit-array
Version:
Useful tools for working with Arrays
43 lines (40 loc) • 1.2 kB
JavaScript
'use strict';
/**
* Filter `null` and `undefined` array items
* @immutable
* @example
* arrayFilterNullable([1, null, 2, undefined, 3, false, 0]); // => [1, 2, 3, false, 0]
* arrayFilterNullable(null); // => []
* arrayFilterNullable(); // => []
*
* // Custom predicate. Use case example #1
* interface A { x: string };
* interface B { x: string; y: string };
* const data: (A | B | null)[] | null = [{ x: '1' }, { x: '2' }, null, { x: '3', y: '4' }];
* const result = arrayFilterNullable(
* data,
* (item): item is B => item != null && 'y' in item
* );
*
* // Custom predicate. Use case example #3
* interface D { x: number; y: string };
* type E = Partial<D>;
* const data: (C | D | null)[] | null = [{ y: 1, x: '2' }, null, { x: '2' }, { y: 4 }];
* const result = arrayFilterNullable(
* data,
* (item): item is D => item != null && item.y != null && item.x !== null
* );
*/
function filterNullable(data, predicate) {
if (predicate === void 0) {
predicate = function (item) {
return item != null;
};
}
if (data == null || !Array.isArray(data)) {
return [];
} else {
return data.filter(predicate);
}
}
module.exports = filterNullable;