object-pickby
Version:
Creates an object composed of the picked object properties. Written in Typescript for ES2019+ environments.
45 lines • 1.88 kB
JavaScript
export function pick(objectOrArray, props) {
if (!objectOrArray)
return objectOrArray;
if (typeof props?.some !== 'function')
return objectOrArray;
if (objectOrArray instanceof Array) {
return props
.filter((i) => {
if (typeof i !== 'number' || !Number.isInteger(i))
throw new TypeError(`While picking from an array we expect array of integer indexes to pick, but got ${String(i)}`);
return Math.abs(i) <= objectOrArray.length;
})
.map(i => objectOrArray[i < 0 ? objectOrArray.length + i : i]);
}
if (typeof objectOrArray !== 'object')
return objectOrArray;
const entries = Object.entries(objectOrArray);
if (props.some(property => typeof property === 'symbol')) {
const symbolProps = Object.getOwnPropertySymbols(objectOrArray).map(symbol => [symbol, objectOrArray[symbol]]);
entries.push(...symbolProps);
}
const properties = new Set(props);
if (properties.size === 0)
return {};
return Object.fromEntries(entries.filter(([property]) => properties.has(property)));
}
export function pickBy(objectOrArray, predicate) {
if (!objectOrArray || typeof predicate !== 'function')
return objectOrArray;
if (objectOrArray instanceof Array) {
return objectOrArray.reduce((accumulator, currentValue, currentIndex) => {
if (predicate(currentValue, currentIndex, accumulator))
accumulator.push(currentValue);
return accumulator;
}, []);
}
return Object.fromEntries([
...Object.entries(objectOrArray),
...Object.getOwnPropertySymbols(objectOrArray).map(symbol => [
symbol,
objectOrArray[symbol],
]),
].filter(([key, value]) => predicate(value, key)));
}
//# sourceMappingURL=index.js.map