Skip to content

Commit 8cc35da

Browse files
committed
Add optimized examples
1 parent 0e76ce9 commit 8cc35da

File tree

2 files changed

+104
-0
lines changed

2 files changed

+104
-0
lines changed

JavaScript/5-each-opt.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
3+
const INTERVAL = 10;
4+
5+
const numbers = new Array(1000).fill(1);
6+
7+
const each = (array, fn) => {
8+
let time = Date.now();
9+
let i = 0;
10+
const last = array.length - 1;
11+
12+
const next = () => {
13+
while (i <= last) {
14+
const now = Date.now();
15+
const diff = now - time;
16+
if (diff > INTERVAL) {
17+
time = now;
18+
setTimeout(next, 0);
19+
break;
20+
} else {
21+
fn(array[i], i++);
22+
}
23+
}
24+
};
25+
26+
next();
27+
};
28+
29+
let k = 0;
30+
31+
const timer = setInterval(() => {
32+
console.log('next ', k++);
33+
}, 10);
34+
35+
const begin = process.hrtime.bigint();
36+
37+
each(numbers, (item, i) => {
38+
console.log(i);
39+
if (i === 999) {
40+
clearInterval(timer);
41+
const diff = (process.hrtime.bigint() - begin) / 1000000n;
42+
console.log('Time(ms):', diff.toString());
43+
console.dir({ k });
44+
}
45+
});

JavaScript/6-for-opt.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
'use strict';
2+
3+
const INTERVAL = 10;
4+
5+
const range = {
6+
start: 1,
7+
end: 1000,
8+
[Symbol.asyncIterator]() {
9+
let time = Date.now();
10+
let value = this.start;
11+
return {
12+
next: () => {
13+
const now = Date.now();
14+
const diff = now - time;
15+
if (diff > INTERVAL) {
16+
time = now;
17+
return new Promise((resolve, reject) => {
18+
setTimeout(() => {
19+
resolve({
20+
value,
21+
done: value++ === this.end + 1
22+
});
23+
}, 0);
24+
});
25+
} else {
26+
return Promise.resolve({
27+
value,
28+
done: value++ === this.end + 1
29+
});
30+
}
31+
}
32+
};
33+
}
34+
};
35+
36+
console.dir({
37+
range,
38+
names: Object.getOwnPropertyNames(range),
39+
symbols: Object.getOwnPropertySymbols(range),
40+
});
41+
42+
let k = 0;
43+
44+
const timer = setInterval(() => {
45+
console.log('next ', k++);
46+
}, 10);
47+
48+
(async () => {
49+
const begin = process.hrtime.bigint();
50+
for await (const number of range) {
51+
console.log(number);
52+
if (number === range.end) {
53+
clearInterval(timer);
54+
}
55+
}
56+
const diff = (process.hrtime.bigint() - begin) / 1000000n;
57+
console.log('Time(ms):', diff.toString());
58+
console.dir({ k });
59+
})();

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy