super-utils-plus
Version:
A superior alternative to Lodash with improved performance, TypeScript support, and developer experience
86 lines (85 loc) • 2.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapValues = mapValues;
exports.mapKeys = mapKeys;
const is_1 = require("../utils/is");
/**
* Creates an object with the same keys as object and values generated by
* running each own enumerable string keyed property of object through
* iteratee. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @param object - The object to iterate over
* @param iteratee - The function invoked per iteration
* @returns The new mapped object
*
* @example
* ```ts
* const users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
* ```
*/
function mapValues(object, iteratee) {
if (!(0, is_1.isObject)(object)) {
return {};
}
// Convert iteratee to a function if it's a string
let iterateeFn;
if (typeof iteratee === 'string') {
const key = iteratee;
iterateeFn = (value) => {
return (0, is_1.isObject)(value) ? value[key] : undefined;
};
}
else {
iterateeFn = iteratee;
}
const result = {};
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
result[key] = iterateeFn(object[key], key, object);
}
}
return result;
}
/**
* Creates an object with the same values as object and keys generated
* by running each own enumerable string keyed property of object through
* iteratee. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @param object - The object to iterate over
* @param iteratee - The function invoked per iteration
* @returns The new mapped object
*
* @example
* ```ts
* mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
* ```
*/
function mapKeys(object, iteratee) {
if (!(0, is_1.isObject)(object)) {
return {};
}
const result = {};
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
const value = object[key];
const newKey = iteratee(value, key, object);
result[newKey] = value;
}
}
return result;
}