-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathscope.js
54 lines (46 loc) · 1.06 KB
/
scope.js
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
"use strict";
let Bluebird = require("bluebird");
let _ = require("lodash");
let temporaries = [];
function scope(f) {
if (_.isFunction(f)) {
scope.begin();
try {
return f.call(scope, scope);
}
finally {
scope.end();
}
}
}
scope.begin = function() {
temporaries.push(new Set());
return scope;
};
scope.end = function() {
if (temporaries.length) {
let set = temporaries[temporaries.length - 1];
temporaries.length--;
free(set);
}
return scope;
};
scope.register = function(array) {
if (temporaries.length && _.isObject(array) && _.isFunction(array.free)) {
let set = temporaries[temporaries.length - 1];
set.add(array);
}
};
scope.result = function(array) {
if (temporaries.length && _.isObject(array)) {
let set = temporaries[temporaries.length - 1];
set.delete(array);
}
return array;
};
function free(arrays) {
for (let array of arrays.values()) {
array.free();
}
}
module.exports = scope;