|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const poolify = (factory, min, norm, max) => { |
| 4 | + |
| 5 | + const duplicate = n => new Array(n).fill().map(() => factory()); |
| 6 | + |
| 7 | + const pool = (par) => { |
| 8 | + if (typeof(par) !== 'function') { |
| 9 | + if (pool.items.length < max) { |
| 10 | + const delayed = pool.delayed.pop(); |
| 11 | + if (delayed) { |
| 12 | + console.log('Recycle item, pass to delayed'); |
| 13 | + delayed(par); |
| 14 | + return; |
| 15 | + } else { |
| 16 | + pool.items.push(par); |
| 17 | + } |
| 18 | + } |
| 19 | + console.log('Recycle item, count =', pool.items.length); |
| 20 | + return; |
| 21 | + } |
| 22 | + if (pool.items.length < min) { |
| 23 | + const items = duplicate(norm - pool.items.length); |
| 24 | + pool.items.push(...items); |
| 25 | + } |
| 26 | + const res = pool.items.pop(); |
| 27 | + console.log('Get from pool, count =', pool.items.length); |
| 28 | + if (res) { |
| 29 | + par(res); |
| 30 | + } else { |
| 31 | + pool.delayed.push(par); |
| 32 | + console.log('Request delayed'); |
| 33 | + } |
| 34 | + return pool; |
| 35 | + }; |
| 36 | + |
| 37 | + return Object.assign(pool, { |
| 38 | + items: duplicate(norm), |
| 39 | + delayed: [] |
| 40 | + }); |
| 41 | + |
| 42 | +}; |
| 43 | + |
| 44 | +// Usage |
| 45 | + |
| 46 | +// Factory to allocate 4kb buffer |
| 47 | +const buffer = () => new Uint32Array(128); |
| 48 | + |
| 49 | +// Allocate pool of 10 buffers |
| 50 | +const pool = poolify(buffer, 0, 5, 10); |
| 51 | + |
| 52 | +let i = 0; |
| 53 | + |
| 54 | +const next = () => { |
| 55 | + pool(item => { |
| 56 | + console.log('Buffer size', item.length * 32); |
| 57 | + i++; |
| 58 | + if (i < 10) { |
| 59 | + setTimeout(next, i * 10); |
| 60 | + setTimeout(() => pool(item), i * 100); |
| 61 | + } |
| 62 | + }); |
| 63 | +}; |
| 64 | + |
| 65 | +next(); |
0 commit comments