From 6dae62595392f9132e99fd687507e036304e7556 Mon Sep 17 00:00:00 2001 From: cha0s Date: Sun, 9 May 2021 02:06:44 -0500 Subject: [PATCH] feat: array destructure --- packages/sandbox/src/sandbox.js | 43 +++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/packages/sandbox/src/sandbox.js b/packages/sandbox/src/sandbox.js index 4ff7de8..cc090f3 100644 --- a/packages/sandbox/src/sandbox.js +++ b/packages/sandbox/src/sandbox.js @@ -26,7 +26,29 @@ export default class Sandbox { } } - destructure(id, init, scope) { + destructureArray(id, init, scope) { + this.setNextScope(id, scope); + const {elements} = id; + for (let i = 0; i < elements.length; ++i) { + const element = elements[i]; + if (null === element) { + // eslint-disable-next-line no-continue + continue; + } + this.setNextScope(element, scope); + if (types.isIdentifier(element)) { + scope.allocate(element.name, init[i]); + } + else { + // eslint-disable-next-line no-console + console.error("destructureArray(): Can't handle type", element.type); + return undefined; + } + } + return undefined; + } + + destructureObject(id, init, scope) { this.setNextScope(id, scope); const {properties} = id; const promises = []; @@ -41,7 +63,7 @@ export default class Sandbox { scope.allocate(name, init[k]); return undefined; } - return this.destructure(property.value, init[k], scope); + return this.destructureObject(property.value, init[k], scope); })); // eslint-disable-next-line no-continue continue; @@ -50,7 +72,7 @@ export default class Sandbox { scope.allocate(property.value.name, init[k.value]); } else { - const promiseOrVoid = this.destructure(property.value, init[k.value], scope); + const promiseOrVoid = this.destructureObject(property.value, init[k.value], scope); if (promiseOrVoid) { promises.push(promiseOrVoid); } @@ -667,10 +689,21 @@ export default class Sandbox { scope.allocate(id.name, init.value); } } + else if (types.isArrayPattern(id)) { + const promiseOrVoid = init.async + ? Promise.resolve(init.value).then((init) => this.destructureArray(id, init, scope)) + : this.destructureArray(id, init.value, scope); + if (promiseOrVoid) { + yield { + async: true, + value: promiseOrVoid, + }; + } + } else if (types.isObjectPattern(id)) { const promiseOrVoid = init.async - ? Promise.resolve(init.value).then((init) => this.destructure(id, init, scope)) - : this.destructure(id, init.value, scope); + ? Promise.resolve(init.value).then((init) => this.destructureObject(id, init, scope)) + : this.destructureObject(id, init.value, scope); if (promiseOrVoid) { yield { async: true,