forked from schteppe/cannon.js
/
Pool.ts
59 lines (52 loc) 路 1.03 KB
/
Pool.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* For pooling objects that can be reused.
*/
export class Pool {
/**
* The objects array.
*/
objects: any[] = []
/**
* The type of the objects.
*/
type: any = Object
/**
* Release an object after use
*/
release(...args: any[]): Pool {
const Nargs = args.length
for (let i = 0; i !== Nargs; i++) {
this.objects.push(args[i])
}
return this
}
/**
* Get an object
*/
get(): any {
if (this.objects.length === 0) {
return this.constructObject()
} else {
return this.objects.pop()
}
}
/**
* Construct an object. Should be implemented in each subclass.
*/
constructObject(): void {
throw new Error('constructObject() not implemented in this Pool subclass yet!')
}
/**
* @return Self, for chaining
*/
resize(size: number): Pool {
const objects = this.objects
while (objects.length > size) {
objects.pop()
}
while (objects.length < size) {
objects.push(this.constructObject())
}
return this
}
}