es-toolkit
Version:
A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.
46 lines (45 loc) • 1.76 kB
JavaScript
import { identity } from "../../function/identity.mjs";
import { isNil } from "../../predicate/isNil.mjs";
import { iteratee } from "../util/iteratee.mjs";
//#region src/compat/object/invertBy.ts
/**
* Creates a new object that reverses the keys and values of the given object, similar to the invert.
*
* The `iteratee` function specifies how the values are reversed into keys. If no `iteratee` function is provided, the values are used as keys as-is.
*
* The values of the new object are arrays of keys that correspond to the value returned by the `iteratee` function.
*
* @param object - The object to iterate over.
* @param [iteratee] - Optional. A function that generates a key based on each value in the object.
* If not provided, the function defaults to using the value as a string.
*
* @returns An object where the keys are generated by the iteratee, and the values
* are arrays of property names (keys) from the input object that correspond to those keys.
*
* @example
* const obj = { a: 1, b: 2, c: 1 };
* const result = invertBy(obj);
* // result => { '1': ['a', 'c'], '2': ['b'] }
*
* @example
* const obj = { a: 1, b: 2, c: 1 };
* const result = invertBy(obj, value => `group${value}`);
* // result => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
function invertBy(object, iteratee$1) {
const result = {};
if (isNil(object)) return result;
if (iteratee$1 == null) iteratee$1 = identity;
const keys = Object.keys(object);
const getString = iteratee(iteratee$1);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = object[key];
const valueStr = getString(value);
if (Array.isArray(result[valueStr])) result[valueStr].push(key);
else result[valueStr] = [key];
}
return result;
}
//#endregion
export { invertBy };