map_values.js (1983B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isFunction = require( '@stdlib/assert/is-function' ); 24 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 25 26 27 // MAIN // 28 29 /** 30 * Maps values from one object to a new object having the same keys. 31 * 32 * ## Notes 33 * 34 * - Iteration order is **not** guaranteed. 35 * - The function only operates on own properties, not inherited properties. 36 * 37 * 38 * @param {Object} obj - source object 39 * @param {Function} transform - transform function 40 * @throws {TypeError} first argument must be an object 41 * @throws {TypeError} second argument must be a function 42 * @returns {Object} new object 43 * 44 * @example 45 * function transform( value, key ) { 46 * return key + value; 47 * } 48 * 49 * var obj1 = { 50 * 'a': 1, 51 * 'b': 2 52 * }; 53 * 54 * var obj2 = mapValues( obj1, transform ); 55 * // returns { 'a': 'a1', 'b': 'b2' } 56 */ 57 function mapValues( obj, transform ) { 58 var out; 59 var key; 60 if ( typeof obj !== 'object' || obj === null ) { 61 throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); 62 } 63 if ( !isFunction( transform ) ) { 64 throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+transform+'`.' ); 65 } 66 out = {}; 67 for ( key in obj ) { 68 if ( hasOwnProp( obj, key ) ) { 69 out[ key ] = transform( obj[ key ], key, obj ); 70 } 71 } 72 return out; 73 } 74 75 76 // EXPORTS // 77 78 module.exports = mapValues;