|
| 1 | +import { isInstanceOf } from "./isInstanceOf"; |
| 2 | +import { isFunction } from "./isFunction"; |
| 3 | +import { isArray } from "./isArray"; |
| 4 | + |
| 5 | +/** |
| 6 | + * Loops though the given object (array, dictionary, NodeList, HTMLCollection) and runs |
| 7 | + * a callback on each item. |
| 8 | + * The callback loop will break when the callback function returns "false" explicitly! |
| 9 | + * |
| 10 | + * @export |
| 11 | + * @template T |
| 12 | + * @param {*} obj |
| 13 | + * @param {((item: T, index: number | string, scope: any) => any | boolean)} callback |
| 14 | + * @param {*} [scope] |
| 15 | + * @returns |
| 16 | + */ |
| 17 | +export function forEach<T>( |
| 18 | + obj: any, |
| 19 | + callback: (item: T, index: number | string, scope: any) => any | boolean, |
| 20 | + scope?: any |
| 21 | +) { |
| 22 | + let key: any; |
| 23 | + const isHTMLCollection = (elObj: any): boolean => { |
| 24 | + return ( |
| 25 | + (elObj.constructor && elObj.constructor.name && elObj.constructor.name === "HTMLCollection") || |
| 26 | + elObj.toString() === "[object HTMLCollection]" |
| 27 | + ); |
| 28 | + }; |
| 29 | + if (obj) { |
| 30 | + if (isFunction(obj)) { |
| 31 | + return; |
| 32 | + } else if (isArray(obj)) { |
| 33 | + // tslint:disable-next-line:no-shadowed-variable |
| 34 | + const length: number = obj.length; |
| 35 | + for (key = 0; key < length; key++) { |
| 36 | + if (callback.call(scope, obj[key], key, obj) === false) { |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | + } else if (isHTMLCollection(obj) || isInstanceOf(obj, NodeList)) { |
| 41 | + const length: number = obj.length; |
| 42 | + let el: HTMLElement; |
| 43 | + for (key = 0; key !== length; key++) { |
| 44 | + el = obj.item(key); |
| 45 | + if (callback.call(scope, el, key, obj) === false) { |
| 46 | + break; |
| 47 | + } |
| 48 | + } |
| 49 | + } else { |
| 50 | + for (key in obj) { |
| 51 | + if (obj.hasOwnProperty(key)) { |
| 52 | + if (callback.call(scope, obj[key], key, obj) === false) { |
| 53 | + break; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments