super-utils-plus
Version:
A superior alternative to Lodash with improved performance, TypeScript support, and developer experience
71 lines (70 loc) • 1.96 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.eachRight = exports.each = void 0;
exports.forEach = forEach;
exports.forEachRight = forEachRight;
/**
* Iterates over elements of collection and invokes iteratee for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning false.
*
* @param collection - The collection to iterate over
* @param iteratee - The function invoked per iteration
* @returns The collection
*
* @example
* ```ts
* forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
* ```
*/
function forEach(collection, iteratee) {
if (!collection || !collection.length) {
return collection;
}
for (let i = 0; i < collection.length; i++) {
const result = iteratee(collection[i], i, collection);
if (result === false) {
break;
}
}
return collection;
}
/**
* This method is like forEach except that it iterates over elements of
* collection from right to left.
*
* @param collection - The collection to iterate over
* @param iteratee - The function invoked per iteration
* @returns The collection
*
* @example
* ```ts
* forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
* ```
*/
function forEachRight(collection, iteratee) {
if (!collection || !collection.length) {
return collection;
}
for (let i = collection.length - 1; i >= 0; i--) {
const result = iteratee(collection[i], i, collection);
if (result === false) {
break;
}
}
return collection;
}
// Aliases
exports.each = forEach;
exports.eachRight = forEachRight;