Skip to content

Commit e653a4f

Browse files
committed
loop tips
1 parent cb3c83c commit e653a4f

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

js-coding-technique/loops.js

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
const mil = 1000000;
2+
const arr = Array(mil);
3+
4+
console.time('⏲️');
5+
6+
for (let i = 0; i < mil; i++) {} // 1.6ms
7+
8+
for (const v of arr) {
9+
} // 11.7ms
10+
11+
arr.forEach(v => v); // 2.1ms
12+
13+
for (let i = mil; i > 0; i--) {} // 1.5ms
14+
15+
console.timeEnd('⏲️');
16+
17+
const equine = { unicorn: '🦄', horse: '🐴', zebra: '🦓' };
18+
19+
for (const key in equine) {
20+
// Filters out properties inherited from prototype
21+
if (equine.hasOwnProperty(key)) {
22+
console.log(equine[key]);
23+
}
24+
}
25+
26+
// Unwrap the the Values
27+
28+
for (const val of Object.values(equine)) {
29+
console.log(val);
30+
}
31+
32+
// Create a Map
33+
const equine = new Map(Object.entries(equine));
34+
35+
for (const v of equine.values()) {
36+
console.log(v);
37+
}
38+
39+
const equine = [
40+
['unicorn', '🦄'],
41+
['horse', '🐴'],
42+
['zebra', '🦓'],
43+
];
44+
45+
// 😒 Meh Code
46+
for (const arr of equine) {
47+
const type = arr[0];
48+
const face = arr[1];
49+
console.log(`${type} looks like ${face}`);
50+
}
51+
52+
// 🤯 Destructured Code
53+
for (const [type, face] of equine) {
54+
console.log(`${type} looks like ${face}`);
55+
}
56+
57+
///////////////
58+
arr[Symbol.iterator] = function () {
59+
let i = 0;
60+
let arr = this;
61+
return {
62+
next: function () {
63+
if (i >= arr.length) {
64+
return { done: true };
65+
} else {
66+
const value = arr[i] + '🙉';
67+
i++;
68+
return { value, done: false };
69+
}
70+
},
71+
};
72+
};
73+
74+
////////////////////////////////
75+
76+
const faces = ['😀', '😍', '🤤', '🤯', '💩', '🤠', '🥳'];
77+
78+
// Transform values
79+
const withIndex = faces.map((v, i) => `face ${i} is ${v}`);
80+
81+
// Test at least one value meets a condition
82+
const isPoopy = faces.some(v => v === '💩');
83+
// false
84+
85+
// Test all values meet a condition
86+
const isEmoji = faces.every(v => v > 'ÿ');
87+
// true
88+
89+
// Filter out values
90+
const withoutPoo = faces.filter(v => v !== '💩');
91+
92+
// Reduce values to a single value
93+
const pooCount = faces.reduce((acc, cur) => {
94+
return acc + (cur === '💩' ? 1 : 0);
95+
}, 0);
96+
console.log(pooCount);
97+
98+
// Sort the values
99+
const sorted = faces.sort((a, b) => a < b);

0 commit comments

Comments
 (0)