super-utils-plus
Version:
A superior alternative to Lodash with improved performance, TypeScript support, and developer experience
62 lines (61 loc) • 1.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.pick = pick;
exports.pickBy = pickBy;
/**
* Creates an object composed of the picked object properties.
*
* @param object - The source object
* @param paths - The property paths to pick
* @returns The new object
*
* @example
* ```ts
* const object = { 'a': 1, 'b': 2, 'c': 3 };
*
* pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
* ```
*/
function pick(object, paths) {
if (!object || !paths.length) {
return {};
}
const result = {};
for (const path of paths) {
if (Object.prototype.hasOwnProperty.call(object, path)) {
result[path] = object[path];
}
}
return result;
}
/**
* Creates an object composed of the object properties predicate returns truthy for.
*
* @param object - The source object
* @param predicate - The function invoked per property
* @returns The new object
*
* @example
* ```ts
* const object = { 'a': 1, 'b': 2, 'c': 3 };
*
* pickBy(object, (value) => value < 3);
* // => { 'a': 1, 'b': 2 }
* ```
*/
function pickBy(object, predicate) {
if (!object) {
return {};
}
const result = {};
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
const value = object[key];
if (predicate(value, key)) {
result[key] = value;
}
}
}
return result;
}