From ba8b84245266589e43c0e70d99e12b981d349809 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20H=C3=BCbelbauer?= Date: Fri, 26 May 2023 18:55:39 +0200 Subject: [PATCH] feat: Add support for the Jekyll sample filter (#612) * Add support for the Jekyll sample filter See https://jekyllrb.com/docs/liquid/filters I am sorting the array randomly and then picking the first N items or all items if there is no sample limit. * Remove incorrect spaces before parens Typo and copy-paste meet --- src/filters/array.ts | 11 +++++++++++ test/integration/filters/array.spec.ts | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/filters/array.ts b/src/filters/array.ts index de29f8d06d..a82b231645 100644 --- a/src/filters/array.ts +++ b/src/filters/array.ts @@ -88,3 +88,14 @@ export function uniq (arr: T[]): T[] { return true }) } + +export function sample (v: T[] | string, count: number | undefined = undefined): T[] | string { + v = toValue(v) + if (isNil(v)) return [] + if (!isArray(v)) { + v = stringify(v) + return [...v].sort(() => Math.random()).slice(0, count).join('') + } + + return [...v].sort(() => Math.random()).slice(0, count) +} diff --git a/test/integration/filters/array.spec.ts b/test/integration/filters/array.spec.ts index 17ddea1777..9df3e7c0b8 100644 --- a/test/integration/filters/array.spec.ts +++ b/test/integration/filters/array.spec.ts @@ -104,6 +104,20 @@ describe('filters/array', function () { expect(html).toBe('abc') }) }) + describe('sample', function () { + it('should return full array sample', () => test( + '{{ "hello,world" | split: "," | sample | size }}', + '2' + )) + it('should return full array sample even if excess count', () => test( + '{{ "hello,world" | split: "," | sample: 10 | size }}', + '2' + )) + it('should return partial array sample', () => test( + '{{ "hello,world" | split: "," | sample: 1 | size }}', + '1' + )) + }) describe('size', function () { it('should return string length', () => test( '{{ "Ground control to Major Tom." | size }}',