time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

map_keys.js (2214B)


      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 keys from one object to a new object having the same values.
     31 *
     32 * ## Notes
     33 *
     34 * -   Iteration order is **not** guaranteed.
     35 * -   We need to cache an object value to prevent the edge case where, during the invocation of the transform function, the value corresponding to a particular key is swapped for some other value. For some, that might be a feature; here, we take the stance that one should be less clever.
     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( key, value ) {
     46 *     return key + value;
     47 * }
     48 *
     49 * var obj1 = {
     50 *     'a': 1,
     51 *     'b': 2
     52 * };
     53 *
     54 * var obj2 = mapKeys( obj1, transform );
     55 * // returns { 'a1': 1, 'b2': 2 }
     56 */
     57 function mapKeys( obj, transform ) {
     58 	var out;
     59 	var key;
     60 	var v;
     61 	if ( typeof obj !== 'object' || obj === null ) {
     62 		throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
     63 	}
     64 	if ( !isFunction( transform ) ) {
     65 		throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+transform+'`.' );
     66 	}
     67 	out = {};
     68 	for ( key in obj ) {
     69 		if ( hasOwnProp( obj, key ) ) {
     70 			v = obj[ key ];
     71 			key = transform( key, v, obj );
     72 			out[ key ] = v;
     73 		}
     74 	}
     75 	return out;
     76 }
     77 
     78 
     79 // EXPORTS //
     80 
     81 module.exports = mapKeys;