UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

98 lines (93 loc) 2.05 kB
/*! * @techmely/utils * Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com> * MIT Licensed */ // src/array.ts function unique(array) { return [...new Set(array)]; } function uniqueObj(items, uniqueKey) { const map = /* @__PURE__ */ new Map(); for (const item of items) { const key = item[uniqueKey]; if (!map.has(key)) { map.set(key, item); } } return [...map.values()]; } function take(array, limit) { return array.slice(0, limit); } function findLastIndex(array, predicate) { let l = array.length; while (l--) { if (predicate(array[l], l, array)) { return l; } } return -1; } function groupBy(list, keyGetter) { const map = /* @__PURE__ */ new Map(); for (const item of list) { const key = keyGetter(item); const collection = map.get(key); if (collection) { collection.push(item); } else { map.set(key, [item]); } } return map; } function remove(arr, el) { const i = arr.indexOf(el); if (i > -1) { arr.splice(i, 1); } } function sample(arr, count) { return Array.from({ length: count }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]); } function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const factor = Math.floor(Math.random() * (i + 1)); [array[i], array[factor]] = [array[factor], array[i]]; } return array; } function chunk(array, size = 1) { if (!array || array.length === 0) { return []; } const chunkLength = Math.ceil(array.length / size); return Array.from({ length: chunkLength }, (_v, i) => { const start = i * size; return array.slice(start, start + size); }); } function normalize(array, key) { if (!array || array.length === 0) return {}; return array.reduce((acc, cur) => { const keyValue = cur[key]; if (keyValue) { return Object.assign(acc, { [keyValue]: cur }); } return acc; }, {}); } export { unique, uniqueObj, take, findLastIndex, groupBy, remove, sample, shuffle, chunk, normalize };