nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
41 lines (40 loc) • 1.42 kB
JavaScript
export const flattenArray = (input) => {
if (!Array.isArray(input))
return [input];
return input.reduce((acc, item) => {
return acc.concat(Array.isArray(item) ? flattenArray(item) : [item]);
}, []);
};
export const filterArrayOfObjects = (array, conditions) => {
if (!Array.isArray(array)) {
throw new Error('The provided input is not a valid array!');
}
return array?.filter((item) => Object.entries(conditions)?.every(([key, conditionFn]) => {
if (typeof conditionFn === 'function') {
return conditionFn(item[key]);
}
return true;
}));
};
export const isInvalidOrEmptyArray = (value) => {
if (!Array.isArray(value))
return true;
if (value?.length === 0)
return true;
return value?.every((item) => item == null ||
(Array.isArray(item) && item?.length === 0) ||
(typeof item === 'object' && Object.keys(item || {})?.length === 0));
};
export const shuffleArray = (array) => {
if (isInvalidOrEmptyArray(array))
return array;
const shuffled = [...array];
for (let i = shuffled?.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
};
export const getLastArrayElement = (array) => {
return array?.length > 0 ? array[array?.length - 1] : undefined;
};