Skip to content

Commit 15b3d8b

Browse files
committed
Optimize: remove mixin with Object.assign
1 parent d0691e0 commit 15b3d8b

2 files changed

Lines changed: 16 additions & 24 deletions

File tree

JavaScript/3-poolify.js

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,19 @@
11
'use strict';
22

33
const poolify = (factory, size) => {
4+
const items = new Array(size).fill(null).map(() => factory());
45

5-
const pool = (item) => {
6+
return (item) => {
67
if (item) {
7-
pool.items.push(item);
8-
console.log('Recycle item, count =', pool.items.length);
8+
items.push(item);
9+
console.log('Recycle item, count =', items.length);
910
return;
1011
}
11-
const res = pool.items.pop() || factory();
12+
const res = items.pop() || factory();
1213

13-
console.log('Get from pool, count =', pool.items.length);
14+
console.log('Get from pool, count =', items.length);
1415
return res;
1516
};
16-
17-
const items = new Array(size).fill().map(() => factory());
18-
return Object.assign(pool, { items });
19-
2017
};
2118

2219
// Usage

JavaScript/4-improved.js

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,25 @@
11
'use strict';
22

33
const poolify = (factory, min, norm, max) => {
4-
54
const duplicate = n => new Array(n).fill().map(() => factory());
5+
const items = duplicate(norm);
66

7-
const pool = (item) => {
7+
return (item) => {
88
if (item) {
9-
if (pool.items.length < max) {
10-
pool.items.push(item);
9+
if (items.length < max) {
10+
items.push(item);
1111
}
12-
console.log('Recycle item, count =', pool.items.length);
12+
console.log('Recycle item, count =', items.length);
1313
return;
1414
}
15-
if (pool.items.length < min) {
16-
const items = duplicate(norm - pool.items.length);
17-
pool.items.push(...items);
15+
if (items.length < min) {
16+
const instances = duplicate(norm - items.length);
17+
items.push(...instances);
1818
}
19-
const res = pool.items.pop();
20-
21-
console.log('Get from pool, count =', pool.items.length);
19+
const res = items.pop();
20+
console.log('Get from pool, count =', items.length);
2221
return res;
2322
};
24-
25-
const items = duplicate(norm);
26-
return Object.assign(pool, { items });
27-
2823
};
2924

3025
// Usage

0 commit comments

Comments
 (0)