foreach
foreach copied to clipboard
Typescript
Hey there,
I'd love to see this in Typescript. I'm pretty new to the game and can't wrap my head around the specs for Array
, I'm always getting errors regarding collection
:
export function forEach(
collection: string[] | Object | NodeList,
callback: Function,
scope: (string | number)[] | Object | NodeList
): void {
if (Object.prototype.toString.call(collection) === '[object Object]') {
for (const prop in collection) {
if (Object.prototype.hasOwnProperty.call(collection, prop)) {
callback.call(scope, collection[prop], prop, collection);
}
}
} else {
for (let index = 0; index < collection.length; index++) {
callback.call(scope, collection[index], index, collection);
}
}
};