-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path3-iteration.js
More file actions
48 lines (34 loc) · 936 Bytes
/
3-iteration.js
File metadata and controls
48 lines (34 loc) · 936 Bytes
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
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';
// Higher-Order Functions & Recursion
// Recursion calls instead of for loops
const numbers = [2, 7, -1, -5, 8];
// Imperative: Manual index management, mutation
for (let i = 0; i < numbers.length; i++) {
const n = numbers[i];
console.log(`Item ${i} is ${n}`);
}
console.log();
// Higher-order function with callback
const loop = (min, max, fn) => {
for (let i = min; i < max; i++) fn(i);
};
loop(0, numbers.length, (i) => {
const n = numbers[i];
console.log(`Item ${i} is ${n}`);
});
console.log();
// Recursion, higher-order functions
const iterate = (arr, fn, i = 0) => {
if (i >= arr.length) return null;
fn(arr[i], i);
return iterate(arr, fn, i + 1);
};
iterate(numbers, (n, i) => {
console.log(`Item ${i} is ${n}`);
});
console.log();
// Built-in higher-order function
const formatItem = (n, i) => `Item ${i} is ${n}`;
numbers.forEach((n, i) => {
console.log(formatItem(n, i));
});