UNPKG

tui-code-snippet

Version:
57 lines (51 loc) 1.78 kB
/** * @fileoverview Execute the provided callback once for each property of object(or element of array) which actually exist. * @author NHN FE Development Lab <dl_javascript@nhn.com> */ 'use strict'; var isArray = require('../type/isArray'); var forEachArray = require('../collection/forEachArray'); var forEachOwnProperties = require('../collection/forEachOwnProperties'); /** * @module collection */ /** * Execute the provided callback once for each property of object(or element of array) which actually exist. * If the object is Array-like object(ex-arguments object), It needs to transform to Array.(see 'ex2' of example). * If the callback function returns false, the loop will be stopped. * Callback function(iteratee) is invoked with three arguments: * 1) The value of the property(or The value of the element) * 2) The name of the property(or The index of the element) * 3) The object being traversed * @param {Object} obj The object that will be traversed * @param {function} iteratee Callback function * @param {Object} [context] Context(this) of callback function * @memberof module:collection * @example * // ES6 * import forEach from 'tui-code-snippet/collection/forEach'; * * // CommonJS * const forEach = require('tui-code-snippet/collection/forEach'); * * let sum = 0; * * forEach([1,2,3], function(value){ * sum += value; * }); * alert(sum); // 6 * * // In case of Array-like object * const array = Array.prototype.slice.call(arrayLike); // change to array * forEach(array, function(value){ * sum += value; * }); */ function forEach(obj, iteratee, context) { if (isArray(obj)) { forEachArray(obj, iteratee, context); } else { forEachOwnProperties(obj, iteratee, context); } } module.exports = forEach;