flooent
Version:
Fluent interface to provide an expressive syntax for common manipulations.
75 lines (74 loc) • 2.35 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.except = exports.only = exports.pull = exports.arrange = exports.mapValues = exports.rename = exports.mapKeys = exports.toObject = void 0;
/**
* Turns the map into an object.
*/
function toObject(value) {
const obj = {};
value.forEach((value, key) => obj[key] = value);
return obj;
}
exports.toObject = toObject;
/**
* Iterates the entries through the given callback and assigns each result as the key.
*/
function mapKeys(value, callback) {
const entries = [...value.entries()];
const mapped = entries.map(([key, value], index) => [callback(value, key, index), value]);
return new Map(mapped);
}
exports.mapKeys = mapKeys;
/**
* Renames the given key with the new key if found, keeping the original insertion order.
*/
function rename(value, oldKey, newKey) {
return mapKeys(value, (_, key) => {
return (key === oldKey) ? newKey : key;
});
}
exports.rename = rename;
/**
* Iterates the entries through the given callback and assigns each result as the value.
*/
function mapValues(value, callback) {
const entries = [...value.entries()];
const mapped = entries.map(([key, value], index) => [key, callback(value, key, index)]);
return new Map(mapped);
}
exports.mapValues = mapValues;
/**
* Rearranges the map to the given keys. Any unmentioned keys will be appended to the end.
*/
function arrange(value, ...keys) {
const rest = new Map(value);
const entries = keys.map(key => {
const value = pull(rest, key);
return [key, value];
});
return new Map(entries.concat([...rest.entries()]));
}
exports.arrange = arrange;
/**
* Returns the value for the given key and deletes the key value pair from the map (mutation).
*/
function pull(value, key) {
const pulled = value.get(key);
value.delete(key);
return pulled;
}
exports.pull = pull;
/**
* Returns a new map with only the given keys.
*/
function only(value, keys) {
return new Map([...value.entries()].filter(([key]) => keys.indexOf(key) >= 0));
}
exports.only = only;
/**
* Inverse of `only`. Returns a new map with all keys except for the given keys.
*/
function except(value, keys) {
return new Map([...value.entries()].filter(([key]) => keys.indexOf(key) === -1));
}
exports.except = except;
;