map-fns
Version:
<h1 align="center"> <code>map-fns</code> </h1>
33 lines (30 loc) • 935 B
JavaScript
;
/**
* Creates a new map populated with every key in `keys` where the value
* behind each `k` in `keys` is `callback(map[k])`.
*
* ```tsx
* mapPartialMap({ a: 1, b: 2, c: 3 }, ["a", "c"], (n) => n * 2);
* //=> {
* // a: 2,
* // c: 6,
* // }
* ```
*
* @param map The original map.
* @param keys The keys to include in the new map.
* @param callback A function that takes a single argument `map[k]` and returns the value of `newMap[k]`.
* @returns A new `map` where `map[k]` is the result of `callback(map[k])`.
*/
function mapPartialMap(map, keys, callback) {
var obj = {};
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
if (!map.hasOwnProperty(key)) {
throw new Error("Key '".concat(key, "' does not exist in map."));
}
obj[key] = callback(map[key]);
}
return obj;
}
module.exports = mapPartialMap;