super-utils-plus
Version:
A superior alternative to Lodash with improved performance, TypeScript support, and developer experience
48 lines (47 loc) • 1.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.invert = invert;
exports.invertBy = invertBy;
const is_1 = require("../utils/is");
/**
* Creates an object composed of the inverted keys and values of object.
*
* @param object - The object to invert
* @returns The inverted object
*/
function invert(object) {
if (!(0, is_1.isObject)(object)) {
return {};
}
const result = {};
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
result[String(object[key])] = key;
}
}
return result;
}
/**
* This method is like `invert` except that the inverted object is generated
* from the results of running each element of object through iteratee.
*
* @param object - The object to invert
* @param iteratee - The iteratee invoked per element
* @returns The grouped inverted object
*/
function invertBy(object, iteratee = value => String(value)) {
if (!(0, is_1.isObject)(object)) {
return {};
}
const result = {};
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
const invertedKey = iteratee(object[key]);
if (!result[invertedKey]) {
result[invertedKey] = [];
}
result[invertedKey].push(key);
}
}
return result;
}