UNPKG

flooent

Version:

Fluent interface to provide an expressive syntax for common manipulations.

59 lines (58 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toMap = exports.toEntries = exports.except = exports.only = exports.pull = exports.rename = exports.mapValues = exports.mapKeys = void 0; /** * Iterates the entries through the given callback and assigns each result as the key. */ function mapKeys(value, callback) { const entries = Object.entries(value); const mapped = entries.map(([key, value], index) => [callback(value, key, index), value]); return Object.fromEntries(mapped); } exports.mapKeys = mapKeys; /** * Iterates the entries through the given callback and assigns each result as the value. */ function mapValues(value, callback) { const entries = Object.entries(value); const mapped = entries.map(([key, value], index) => [key, callback(value, key, index)]); return Object.fromEntries(mapped); } exports.mapValues = mapValues; function rename(value, oldKey, newKey) { return mapKeys(value, (_, key) => { return (key === oldKey) ? newKey : key; }); } exports.rename = rename; function pull(value, key) { const pulled = value[key]; delete value[key]; return pulled; } exports.pull = pull; function only(value, keys) { return Object.fromEntries(Object.entries(value).filter(([key]) => keys.includes(key))); } exports.only = only; /** * Inverse of `only`. Returns a new map with all keys except for the given keys. */ function except(value, keys) { return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key))); } exports.except = except; function toEntries(obj) { let ownProps = Object.keys(obj); let i = ownProps.length; let resArray = new Array(i); // preallocate the Array while (i--) resArray[i] = [ownProps[i], obj[ownProps[i]]]; return resArray; } exports.toEntries = toEntries; function toMap(obj) { const entries = toEntries(obj); return new Map(entries); } exports.toMap = toMap;