From dbc049738633b1b6f578d9d20f830b548ba67a22 Mon Sep 17 00:00:00 2001 From: Harttle Date: Sun, 20 Feb 2022 13:02:50 +0800 Subject: [PATCH] fix: sort filter unexpectedly modifies original array, #475 --- docs/themes/navy/layout/partial/all-contributors.swig | 2 ++ src/builtin/filters/array.ts | 2 +- src/template/output.ts | 2 +- test/integration/builtin/filters/array.ts | 4 ++++ 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/themes/navy/layout/partial/all-contributors.swig b/docs/themes/navy/layout/partial/all-contributors.swig index efcbd2c5e..93efd6030 100644 --- a/docs/themes/navy/layout/partial/all-contributors.swig +++ b/docs/themes/navy/layout/partial/all-contributors.swig @@ -53,6 +53,8 @@ + + diff --git a/src/builtin/filters/array.ts b/src/builtin/filters/array.ts index ade6e1128..8cce3efd0 100644 --- a/src/builtin/filters/array.ts +++ b/src/builtin/filters/array.ts @@ -12,7 +12,7 @@ export const reverse = (v: any[]) => [...v].reverse() export function sort (this: FilterImpl, arr: T[], property?: string) { const getValue = (obj: Scope) => property ? this.context.getFromScope(obj, property.split('.')) : obj - return toArray(arr).sort((lhs, rhs) => { + return [...toArray(arr)].sort((lhs, rhs) => { lhs = getValue(lhs) rhs = getValue(rhs) return lhs < rhs ? -1 : (lhs > rhs ? 1 : 0) diff --git a/src/template/output.ts b/src/template/output.ts index 41212faa8..a4d4508f1 100644 --- a/src/template/output.ts +++ b/src/template/output.ts @@ -12,7 +12,7 @@ export class Output extends TemplateImpl implements Template { super(token) this.value = new Value(token.content, liquid) } - public * render (ctx: Context, emitter: Emitter): Generator { + public * render (ctx: Context, emitter: Emitter): IterableIterator { const val = yield this.value.value(ctx, false) emitter.write(val) } diff --git a/test/integration/builtin/filters/array.ts b/test/integration/builtin/filters/array.ts index f28941dcd..2a119f429 100644 --- a/test/integration/builtin/filters/array.ts +++ b/test/integration/builtin/filters/array.ts @@ -138,6 +138,10 @@ describe('filters/array', function () { const c = { name: { first: 'Carol' } } return test(tpl, { arr: [b, c, a, c] }, 'Alice Bob Carol Carol') }) + it('should not change the original array', () => { + const arr = ["one", "two", "three", "four", "five"] + return test("{{arr | sort}} {{arr}}", { arr }, 'fivefouronethreetwo onetwothreefourfive') + }) }) describe('uniq', function () { it('should uniq string list', function () {