map-fns
Version:
<h1 align="center"> <code>map-fns</code> </h1>
60 lines (53 loc) • 2.18 kB
JavaScript
'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
/**
* Creates a new `map` populated with every key in the original `map` where the
* value behind each `k` in `keys` is the return value of `fn(map[k])`
*
* ```tsx
* const out = modifyInMap({ a: 1, b: 2 }, "b", n => n + 1);
* console.log(out); // { a: 1, b: 3 }
* ```
*
* The original `map` is not modified.
*
* An error is thrown if any key in `keys` does not exist in the map.
*
* @param map - The map to copy and modify.
* @param keys - The keys to modify within the map.
* @returns A new map with modified values.
*/
function modifyInMap(map, keys, fn) {
var obj = __assign({}, map);
var keyList = (Array.isArray(keys) ? keys : [keys]);
for (var _i = 0, keyList_1 = keyList; _i < keyList_1.length; _i++) {
var key = keyList_1[_i];
if (!obj.hasOwnProperty(key)) {
throw new Error("Key '".concat(key, "' does not exist in map."));
}
obj[key] = fn(obj[key]);
}
return obj;
}
module.exports = modifyInMap;