UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

79 lines (78 loc) 2.82 kB
import { isValidArray } from '../guards/non-primitives.js'; import { isNumber } from '../guards/primitives.js'; import { isDeepEqual } from '../utils/index.js'; import { _resolveNestedKey } from './helpers.js'; export function createOptionsArray(data, config) { const { firstFieldKey, secondFieldKey, firstFieldName = 'value', secondFieldName = 'label', retainNumberValue = false, } = config || {}; if (data?.length) { return data?.map((datum) => { const firstValue = retainNumberValue && isNumber(datum[firstFieldKey]) ? datum[firstFieldKey] : String(datum[firstFieldKey] ?? ''); return { [firstFieldName]: firstValue, [secondFieldName]: String(datum[secondFieldKey] ?? ''), }; }); } else { return []; } } export function removeDuplicatesFromArray(array) { return array?.filter((item, index, self) => index === self?.findIndex((el) => isDeepEqual(el, item))); } export function getDuplicates(array) { const seen = []; const duplicates = []; for (const item of array) { const hasSeen = seen?.find((el) => isDeepEqual(el, item)); const hasDuplicate = duplicates?.find((el) => isDeepEqual(el, item)); if (hasSeen && !hasDuplicate) { duplicates?.push(item); } else if (!hasSeen) { seen?.push(item); } } return duplicates; } export function findMissingElements(array1, array2, missingFrom) { const source = (missingFrom === 'from-first' ? array1 : array2) ?? []; const target = (missingFrom === 'from-first' ? array2 : array1) ?? []; return source.filter((s) => !target?.some((t) => isDeepEqual(t, s))); } export function splitArray(arr, chunkSize) { const result = []; for (let i = 0; i < arr?.length; i += chunkSize) { result.push(arr.slice(i, i + chunkSize)); } return result; } export function splitArrayByProperty(source, property) { if (!isValidArray(source)) return []; const grouped = {}; source.forEach((item) => { const rawKey = _resolveNestedKey(item, property); const key = rawKey != null ? String(rawKey) : '__undefined__'; if (!grouped[key]) { grouped[key] = []; } grouped[key].push(item); }); return Object.values(grouped); } export function rotateArray(arr, steps) { const length = arr?.length; if (length === 0) return arr; const offset = ((steps % length) + length) % length; return arr.slice(-offset).concat(arr.slice(0, -offset)); } export function moveArrayElement(arr, fromIndex, toIndex) { const newArr = [...arr]; const [item] = newArr.splice(fromIndex, 1); newArr.splice(toIndex, 0, item); return newArr; }