time-to-botec

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

dset.js (1798B)


      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 isObjectLike = require( '@stdlib/assert/is-object-like' );
     24 var hasOwnProp = require( '@stdlib/assert/has-own-property' );
     25 var isFunction = require( '@stdlib/assert/is-function' );
     26 
     27 
     28 // MAIN //
     29 
     30 /**
     31 * Sets a nested property.
     32 *
     33 * @private
     34 * @param {ObjectLike} obj - input object
     35 * @param {Array} props - list of properties defining a key path
     36 * @param {boolean} create - boolean indicating whether to create a path if the key path does not already exist
     37 * @param {*} val - value to set
     38 * @returns {boolean} boolean indicating if the property was successfully set
     39 */
     40 function deepSet( obj, props, create, val ) {
     41 	var bool;
     42 	var len;
     43 	var v;
     44 	var p;
     45 	var i;
     46 
     47 	len = props.length;
     48 	bool = false;
     49 	v = obj;
     50 	for ( i = 0; i < len; i++ ) {
     51 		p = props[ i ];
     52 		if ( isObjectLike( v ) ) {
     53 			if ( !hasOwnProp( v, p ) ) {
     54 				if ( create ) {
     55 					v[ p ] = {};
     56 				} else {
     57 					break;
     58 				}
     59 			}
     60 			if ( i === len-1 ) {
     61 				if ( isFunction( val ) ) {
     62 					v[ p ] = val( v[ p ] );
     63 				} else {
     64 					v[ p ] = val;
     65 				}
     66 				bool = true;
     67 			} else {
     68 				v = v[ p ];
     69 			}
     70 		} else {
     71 			break;
     72 		}
     73 	}
     74 	return bool;
     75 }
     76 
     77 
     78 // EXPORTS //
     79 
     80 module.exports = deepSet;