35 lines
1.3 KiB
JavaScript
35 lines
1.3 KiB
JavaScript
|
|
import { identity } from "../../function/identity.mjs";
|
||
|
|
import { range } from "../../math/range.mjs";
|
||
|
|
import { isArrayLike } from "../predicate/isArrayLike.mjs";
|
||
|
|
//#region src/compat/array/forEach.ts
|
||
|
|
/**
|
||
|
|
* Iterates over each element of the object invoking the provided callback function for each property.
|
||
|
|
*
|
||
|
|
* @template T - The type of object.
|
||
|
|
* @param {T} object - The object to iterate over.
|
||
|
|
* @param {(value: T[keyof T], key: keyof T, object: T) => unknown} [callback] - The function invoked for each property.
|
||
|
|
* The callback function receives three arguments:
|
||
|
|
* - 'value': The current property being processed in the object.
|
||
|
|
* - 'key': The key of the current property being processed in the object.
|
||
|
|
* - 'object': The object 'forEach' was called upon.
|
||
|
|
* @returns {T} Returns the original object.
|
||
|
|
*
|
||
|
|
* @example
|
||
|
|
* forEach({'a': 1, 'b': 2 }, (value, key, object) => console.log(value, key));
|
||
|
|
* // Output:
|
||
|
|
* // 1 'a'
|
||
|
|
* // 2 'b'
|
||
|
|
*/
|
||
|
|
function forEach(collection, callback = identity) {
|
||
|
|
if (!collection) return collection;
|
||
|
|
const keys = isArrayLike(collection) || Array.isArray(collection) ? range(0, collection.length) : Object.keys(collection);
|
||
|
|
for (let i = 0; i < keys.length; i++) {
|
||
|
|
const key = keys[i];
|
||
|
|
const value = collection[key];
|
||
|
|
if (callback(value, key, collection) === false) break;
|
||
|
|
}
|
||
|
|
return collection;
|
||
|
|
}
|
||
|
|
//#endregion
|
||
|
|
export { forEach };
|