time-to-botec

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

for_in.js (1969B)


      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 
     25 
     26 // MAIN //
     27 
     28 /**
     29 * Invokes a function once for each own and inherited enumerable property of an object.
     30 *
     31 * ## Notes
     32 *
     33 * -   Iteration order is **not** guaranteed.
     34 *
     35 *
     36 * @param {Object} obj - input object
     37 * @param {Function} fcn - function to invoke
     38 * @param {*} [thisArg] - execution context
     39 * @throws {TypeError} first argument must be an object
     40 * @throws {TypeError} second argument must be a function
     41 * @returns {Object} obj - input object
     42 *
     43 * @example
     44 * function log( v, key ) {
     45 *     console.log( '%s: %d', key, v );
     46 * }
     47 *
     48 * function Foo() {
     49 *     this.a = 1;
     50 *     this.b = 2;
     51 *     return this;
     52 * }
     53 *
     54 * Foo.prototype.c = 3;
     55 * Foo.prototype.d = 4;
     56 *
     57 * var obj = new Foo();
     58 *
     59 * forIn( obj, log );
     60 */
     61 function forIn( obj, fcn, thisArg ) {
     62 	var bool;
     63 	var key;
     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 	for ( key in obj ) { // eslint-disable-line guard-for-in
     71 		bool = fcn.call( thisArg, obj[ key ], key, obj );
     72 		if ( bool === false ) {
     73 			return obj;
     74 		}
     75 	}
     76 	return obj;
     77 }
     78 
     79 
     80 // EXPORTS //
     81 
     82 module.exports = forIn;