Merge pull request #80 from shrinktofit/node-events

fix recycle-pool
This commit is contained in:
Weiliang Wang
2019-01-21 13:45:04 +08:00
committed by GitHub
@@ -1,31 +1,32 @@
import sort from './timsort';
export default class RecyclePool {
constructor(fn, size) {
export default class RecyclePool<T = any> {
private _fn: () => T;
private _count = 0;
private _data: T[];
constructor (fn: () => T, size: number) {
this._fn = fn;
this._count = 0;
this._data = new Array(size);
this._objIdx = {};
for (let i = 0; i < size; ++i) {
this._data[i] = fn();
this._objIdx[this._data[i]] = i;
}
}
get length() {
get length () {
return this._count;
}
get data() {
get data () {
return this._data;
}
reset() {
public reset () {
this._count = 0;
}
resize(size) {
public resize (size: number) {
if (size > this._data.length) {
for (let i = this._data.length; i < size; ++i) {
this._data[i] = this._fn();
@@ -33,7 +34,7 @@ export default class RecyclePool {
}
}
add() {
public add () {
if (this._count >= this._data.length) {
this.resize(this._data.length * 2);
}
@@ -41,25 +42,26 @@ export default class RecyclePool {
return this._data[this._count++];
}
removeAt(idx) {
public removeAt (idx: number) {
if (idx >= this._count) {
return;
}
let last = this._count - 1;
let tmp = this._data[idx];
const last = this._count - 1;
const tmp = this._data[idx];
this._data[idx] = this._data[last];
this._data[last] = tmp;
this._objIdx[this._data[idx]] = idx;
this._objIdx[this._data[last]] = last;
this._count -= 1;
}
remove(obj) {
this.removeAt(this._objIdx[obj]);
public remove (element: T) {
const idx = this.data.indexOf(element);
if (idx >= 0) {
this.removeAt(idx);
}
}
sort(cmp) {
return sort(this._data, 0, this._count, cmp);
public sort (compare: (a: T, b: T) => number) {
return sort(this._data, 0, this._count, compare);
}
}