Skip to content

Commit

Permalink
feat: Add support for the Jekyll sample filter (#612)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
TomasHubelbauer authored May 26, 2023
1 parent dca9ab5 commit ba8b842
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/filters/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,14 @@ export function uniq<T> (arr: T[]): T[] {
return true
})
}

export function sample<T> (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)
}
14 changes: 14 additions & 0 deletions test/integration/filters/array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}',
Expand Down

0 comments on commit ba8b842

Please sign in to comment.