time-to-botec

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

for_own.js (1985B)


      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 objectKeys = require( './../../keys' );
     24 var isFunction = require( '@stdlib/assert/is-function' );
     25 
     26 
     27 // MAIN //
     28 
     29 /**
     30 * Invokes a function once for each own enumerable property of an object.
     31 *
     32 * ## Notes
     33 *
     34 * -   Iteration order is **not** guaranteed.
     35 *
     36 *
     37 * @param {Object} obj - input object
     38 * @param {Function} fcn - function to invoke
     39 * @param {*} [thisArg] - execution context
     40 * @throws {TypeError} first argument must be an object
     41 * @throws {TypeError} second argument must be a function
     42 * @returns {Object} obj - input object
     43 *
     44 * @example
     45 * function log( v, key ) {
     46 *     console.log( '%s: %d', key, v );
     47 * }
     48 *
     49 * var obj = {
     50 *     'a': 1,
     51 *     'b': 2,
     52 *     'c': 3,
     53 *     'd': 4
     54 * };
     55 *
     56 * forOwn( obj, log );
     57 */
     58 function forOwn( obj, fcn, thisArg ) {
     59 	var keys;
     60 	var bool;
     61 	var len;
     62 	var k;
     63 	var i;
     64 	if ( typeof obj !== 'object' || obj === null ) {
     65 		throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
     66 	}
     67 	if ( !isFunction( fcn ) ) {
     68 		throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+fcn+'`.' );
     69 	}
     70 	keys = objectKeys( obj );
     71 	len = keys.length;
     72 	for ( i = 0; i < len; i++ ) {
     73 		k = keys[ i ];
     74 		bool = fcn.call( thisArg, obj[ k ], k, obj );
     75 		if ( bool === false ) {
     76 			return obj;
     77 		}
     78 	}
     79 	return obj;
     80 }
     81 
     82 
     83 // EXPORTS //
     84 
     85 module.exports = forOwn;