@bushbass/each.js
JavaScript

How to write your own forEach() in JS

repl talk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const each = function(collection, iterator) {
  if (Array.isArray(collection)) {
    for (let i = 0; i < collection.length; i++) {
      iterator(collection[i], i, collection);
    }
  } else {
    for (let key in collection) {
      iterator(collection[key], key, collection);
    }
  }
};

// Inputs for testing
const testArray = [1, 2, 3, 4, 5];
const testArrayFunction = item => console.log(item);
const testObject = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five' };
const testObjectFunction = (item, index) => {
  console.log(`value = ${item} : key =  ${index}`);
};
const testArrayFunctionMore = (item, i, array) => {
  console.log(`Value = ${item}, index = ${i}, orignal array = ${array}`);
};

// test with an array
each(testArray, testArrayFunction);

console.log('\n********** \n');

// test with an Object
each(testObject, testObjectFunction);

console.log('\n********** \n');

// Add access to index and orignal array
each(testArray, testArrayFunctionMore);
Native Browser JavaScript