From 367f062e4e745b811f264c10caa16e9d8a35709a Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 2 May 2018 20:57:46 -0400 Subject: [PATCH] fix and simplify cycle detection --- store.js | 18 +++++++++--------- test/store/index.js | 5 +++-- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/store.js b/store.js index ddb7941527..c5b569c6a8 100644 --- a/store.js +++ b/store.js @@ -50,29 +50,29 @@ assign(Store.prototype, { var computed = this._computed; var sorted = this._sortedComputedProperties = []; var visited = blankObject(); - var cycles = blankObject(); + var currentKey; function visit(key) { - if (visited[key]) return; - visited[key] = true; - var c = computed[key]; if (c) { - if (!cycles[key]) cycles[key] = blankObject(); c.deps.forEach(dep => { - if (cycles[dep] && cycles[dep][key]) { + if (dep === currentKey) { throw new Error(`Cyclical dependency detected between ${dep} <-> ${key}`); } - cycles[key][dep] = true; + visit(dep); }); - sorted.push(c); + + if (!visited[key]) { + visited[key] = true; + sorted.push(c); + } } } for (var key in this._computed) { - visit(key); + visit(currentKey = key); } }, diff --git a/test/store/index.js b/test/store/index.js index daba075bfb..8d5dd5749c 100644 --- a/test/store/index.js +++ b/test/store/index.js @@ -141,8 +141,9 @@ describe('store', () => { assert.throws(() => { store.compute('a', ['b'], b => b + 1); - store.compute('b', ['a'], a => a + 1); - }, /Cyclical dependency detected/); + store.compute('b', ['c'], c => c + 1); + store.compute('c', ['a'], a => a + 1); + }, /Cyclical dependency detected between a <-> c/); }); it('does not falsely report cycles', () => {