Skip to content
This repository was archived by the owner on Jan 31, 2025. It is now read-only.

Commit 7d2db1b

Browse files
author
Daniel Brain
committed
Add cleanup.js
1 parent 51b903a commit 7d2db1b

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

src/lib/cleanup.js

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
2+
import { SyncPromise as Promise } from 'sync-browser-mocks/src/promise';
3+
4+
export function cleanup(obj) {
5+
6+
let tasks = [];
7+
8+
return {
9+
10+
getters: {
11+
array: () => { return []; },
12+
object: () => { return {}; }
13+
},
14+
15+
set(name, item) {
16+
obj[name] = item;
17+
this.register(() => {
18+
delete obj[name];
19+
});
20+
return item;
21+
},
22+
23+
push(collection, item) {
24+
collection.push(item);
25+
this.register(() => {
26+
let index = collection.indexOf(item);
27+
if (index !== -1) {
28+
collection.splice(index, 1);
29+
}
30+
});
31+
return item;
32+
},
33+
34+
setItem(mapping, key, item) {
35+
mapping[key] = item;
36+
this.register(() => {
37+
delete mapping[key];
38+
});
39+
return item;
40+
},
41+
42+
register(name, method) {
43+
44+
if (!method) {
45+
method = name;
46+
name = undefined;
47+
}
48+
49+
tasks.push({
50+
complete: false,
51+
52+
name,
53+
54+
run() {
55+
56+
if (this.complete) {
57+
return;
58+
}
59+
60+
this.complete = true;
61+
62+
return method();
63+
}
64+
});
65+
},
66+
67+
hasTasks() {
68+
return Boolean(tasks.filter(item => !item.complete).length);
69+
},
70+
71+
all() {
72+
let results = [];
73+
74+
while (tasks.length) {
75+
results.push(tasks.pop().run());
76+
}
77+
78+
return Promise.all(results).then(() => {
79+
return;
80+
});
81+
},
82+
83+
run(name) {
84+
let results = [];
85+
let toClean = [];
86+
87+
for (let item of tasks) {
88+
if (item.name === name) {
89+
toClean.push(item);
90+
results.push(item.run());
91+
}
92+
}
93+
94+
for (let item of toClean) {
95+
tasks.splice(tasks.indexOf(item), 1);
96+
}
97+
98+
return Promise.all(results).then(() => {
99+
return;
100+
});
101+
}
102+
};
103+
}

0 commit comments

Comments
 (0)