Skip to content

Commit

Permalink
refactor: use a lookup rather than an array for active handles
Browse files Browse the repository at this point in the history
  • Loading branch information
benlesh committed Dec 15, 2019
1 parent 1b6775f commit b90b397
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
2 changes: 1 addition & 1 deletion spec/util/Immediate-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('Immediate', () => {

setTimeout(() => {
const number = TestTools.pending();
expect(number).to.not.equal(2);
expect(number).to.equal(0);
done();
});
});
Expand Down
11 changes: 5 additions & 6 deletions src/internal/util/Immediate.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
let nextHandle = 1;
const RESOLVED = (() => Promise.resolve())();
const activeHandles: number[] = [];
const activeHandles: { [key: number]: any } = {};

/**
* Finds the handle in the list of active handles, and removes it.
* Returns `true` if found, `false` otherwise. Used both to clear
* Immediate scheduled tasks, and to identify if a task should be scheduled.
*/
function findAndClearHandle(handle: number): boolean {
const i = activeHandles.indexOf(handle);
if (i >= 0) {
activeHandles.splice(i, 1);
if (handle in activeHandles) {
delete activeHandles[handle];
return true;
}
return false;
Expand All @@ -22,7 +21,7 @@ function findAndClearHandle(handle: number): boolean {
export const Immediate = {
setImmediate(cb: () => void): number {
const handle = nextHandle++;
activeHandles.push(handle);
activeHandles[handle] = true;
RESOLVED.then(() => findAndClearHandle(handle) && cb());
return handle;
},
Expand All @@ -37,6 +36,6 @@ export const Immediate = {
*/
export const TestTools = {
pending() {
return activeHandles.length;
return Object.keys(activeHandles).length;
}
};

0 comments on commit b90b397

Please sign in to comment.