diff --git a/packages/runner/src/Runner.js b/packages/runner/src/Runner.js index 1b5b8fc..3c645a4 100644 --- a/packages/runner/src/Runner.js +++ b/packages/runner/src/Runner.js @@ -48,6 +48,7 @@ { this.items = []; this._name = name; + this._aliasCount = 0; } /** @@ -63,14 +64,30 @@ const { name, items } = this; + this._aliasCount++; + for (let i = 0, len = items.length; i < len; i++) { items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); } + if (items === this.items) + { + this._aliasCount--; + } + return this; } + ensureNonAliasedItems() + { + if (this._aliasCount > 0 && this.items.length > 1) + { + this._aliasCount = 0; + this.items = this.items.slice(0); + } + } + /** * Add a listener to the Runner * @@ -92,6 +109,7 @@ { if (item[this._name]) { + this.ensureNonAliasedItems(); this.remove(item); this.items.push(item); } @@ -109,6 +127,7 @@ if (index !== -1) { + this.ensureNonAliasedItems(); this.items.splice(index, 1); } @@ -129,6 +148,7 @@ */ removeAll() { + this.ensureNonAliasedItems(); this.items.length = 0; return this; diff --git a/packages/runner/src/Runner.js b/packages/runner/src/Runner.js index 1b5b8fc..3c645a4 100644 --- a/packages/runner/src/Runner.js +++ b/packages/runner/src/Runner.js @@ -48,6 +48,7 @@ { this.items = []; this._name = name; + this._aliasCount = 0; } /** @@ -63,14 +64,30 @@ const { name, items } = this; + this._aliasCount++; + for (let i = 0, len = items.length; i < len; i++) { items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); } + if (items === this.items) + { + this._aliasCount--; + } + return this; } + ensureNonAliasedItems() + { + if (this._aliasCount > 0 && this.items.length > 1) + { + this._aliasCount = 0; + this.items = this.items.slice(0); + } + } + /** * Add a listener to the Runner * @@ -92,6 +109,7 @@ { if (item[this._name]) { + this.ensureNonAliasedItems(); this.remove(item); this.items.push(item); } @@ -109,6 +127,7 @@ if (index !== -1) { + this.ensureNonAliasedItems(); this.items.splice(index, 1); } @@ -129,6 +148,7 @@ */ removeAll() { + this.ensureNonAliasedItems(); this.items.length = 0; return this; diff --git a/packages/runner/test/index.js b/packages/runner/test/index.js index fcc7f86..dfe384d 100644 --- a/packages/runner/test/index.js +++ b/packages/runner/test/index.js @@ -128,4 +128,32 @@ complete.add(obj).add(obj); expect(complete.items.length).to.equal(1); }); + + it('should not not bug out is items are removed items whilst mid run', function () + { + const complete = new Runner('complete'); + + const objs = []; + let tick = 0; + + for (let i = 0; i < 10; i++) + { + // eslint-disable-next-line no-loop-func + const obj = { complete() + { + tick++; + complete.remove(obj); + } }; + + obj.id = i; + objs.push(obj); + + complete.add(obj); + } + + complete.run(); + + expect(complete.items.length).to.equal(0); + expect(tick).to.equal(10); + }); });