From a764bdf397c33ae7945fb45841e7bd4e4f12f23b Mon Sep 17 00:00:00 2001 From: siubaak Date: Sun, 2 Feb 2025 22:25:17 +0800 Subject: [PATCH] [fix] enhance behaviour of spread element --- src/evaluate/expression.ts | 16 ++++++++-------- tests/expression.test.ts | 4 +++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/evaluate/expression.ts b/src/evaluate/expression.ts index 21cb76b..8a219a6 100644 --- a/src/evaluate/expression.ts +++ b/src/evaluate/expression.ts @@ -36,7 +36,7 @@ export function* ObjectExpression(node: acorn.ObjectExpression, scope: Scope) { for (let i = 0; i < node.properties.length; i++) { const property = node.properties[i] if (property.type === 'SpreadElement') { - assign(object, yield* SpreadElement(property, scope)) + assign(object, yield* SpreadElement(property, scope, { spreadProps: true })) } else { let key: string const propKey = property.key @@ -542,19 +542,19 @@ export interface SuperOptions { getProto?: boolean } -export function* Super( - node: acorn.Super, - scope: Scope, - options: SuperOptions = {}, -) { +export function* Super(node: acorn.Super, scope: Scope, options: SuperOptions = {}) { const { getProto = false } = options const superClass = scope.find(SUPER).get() return getProto ? superClass.prototype: superClass } -export function* SpreadElement(node: acorn.SpreadElement, scope: Scope) { +export interface SpreadOptions { + spreadProps?: boolean +} + +export function* SpreadElement(node: acorn.SpreadElement, scope: Scope, options: SpreadOptions = {}) { const result = yield* evaluate(node.argument, scope) - return typeof result === 'string' ? [...result] : result; + return options.spreadProps ? result : [...result] } export function* ChainExpression(node: acorn.ChainExpression, scope: Scope) { diff --git a/tests/expression.test.ts b/tests/expression.test.ts index 361a839..f8c27ef 100644 --- a/tests/expression.test.ts +++ b/tests/expression.test.ts @@ -167,11 +167,12 @@ describe('testing src/expression.ts', () => { const arr = [1, 2] exports.a = [...arr] exports.b = [...[1, 2, 3]] - + f(...arr) function f(m, n) { exports.c = m exports.d = n + exports.f = [...arguments] } `) @@ -179,6 +180,7 @@ describe('testing src/expression.ts', () => { expect(interpreter.exports.b).toEqual([1, 2, 3]) expect(interpreter.exports.c).toBe(1) expect(interpreter.exports.d).toBe(2) + expect(interpreter.exports.f).toEqual([1, 2]) }) it('should parse regular expression normally', () => {