softkave-js-utils
Version:
JavaScript & Typescript utility functions, types, and classes
81 lines • 2.77 kB
JavaScript
import { get } from 'lodash-es';
import { convertToArray } from './convertToArray.js';
function defaultIndexer(data, path) {
if (path) {
return get(data, path);
}
if (data && data.toString) {
return data.toString();
}
return String(data);
}
function defaultReducer(data) {
return data;
}
/**
* Indexes an array into an object
*
* ```typescript
* // Index an array of JS literals
* const literalRecord = indexArray([1, 2, 3], {indexer: current => current});
* literalRecord === {1: 1, 2: 2, 3: 3};
*
* // Index and transform an array of JS literals
* const literalRecordTransformed = indexArray([1, 2, 3], {
* indexer: current => current,
* reducer: (current, index) => current + index,
* });
* literalRecordTransformed === {1: 1, 2: 3, 3: 5};
*
* // Index an array of JS objects using `path`
* const objRecordByPath = indexArray([{key: 'value01'}, {key: 'value02'}], {
* path: 'key',
* });
* objRecordByPath === {value01: {key: 'value01'}, value02: {key: 'value02'}};
*
* // Index and transform an array of JS object using `path`
* const objRecordByPathTransformed = indexArray(
* [{key: 'value01'}, {key: 'value02'}],
* {path: 'key', reducer: current => current.key}
* );
* objRecordByPathTransformed === {value01: 'value01', value02: 'value02'};
*
* // Index an array of JS objects using an indexer
* const objRecordByIndexer = indexArray([{key: 'value01'}, {key: 'value02'}], {
* indexer: current => current.key,
* });
* objRecordByIndexer === {value01: {key: 'value01'}, value02: {key: 'value02'}};
*
* // Index an array of JS objects using lodash-like dot-separated `path`
* const objRecordByLodashPath = indexArray(
* [{key: {innerKey: ['value01']}}, {key: {innerKey: ['value02']}}],
* {path: 'key.innerKey.0'}
* );
* objRecordByLodashPath ===
* {
* value01: {key: {innerKey: ['value01']}},
* value02: {key: {innerKey: ['value02']}},
* };
* ```
*/
export function indexArray(
/** Array to index */
arr = [], opts) {
var _a, _b;
const array = convertToArray(arr !== null && arr !== void 0 ? arr : []);
const indexer = (_a = opts.indexer) !== null && _a !== void 0 ? _a : defaultIndexer;
const path = opts.path;
const reducer = (_b = opts.reducer) !== null && _b !== void 0 ? _b : defaultReducer;
if (typeof indexer !== 'function') {
if (typeof path !== 'string') {
return {};
}
}
const result = array.reduce((accumulator, current, index) => {
const key = indexer(current, path, index, array);
accumulator[key] = reducer(current, index, array, accumulator[key], accumulator);
return accumulator;
}, {});
return result;
}
//# sourceMappingURL=indexArray.js.map