Skip to content

Commit

Permalink
feat: compact filter
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Feb 4, 2021
1 parent ec4a711 commit f42c217
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
6 changes: 3 additions & 3 deletions docs/source/zh-cn/filters/compact.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
title: compact
---

Removes any `nil` values from an array.
从数组里移除任何 `null``undefined` 值。

For this example, assume `site.pages` is an array of content pages for a website, and some of these pages have an attribute called `category` that specifies their content category. If we `map` those categories to an array, some of the array items might be `nil` if any pages do not have a `category` attribute.
假设 `site.pages` 是网页列表,有些网页包含 `category` 属性用来标明类别。如果把它们 `map` 到数组里,那么对于没有 `category` 属性的元素就会是 `undefined`

输入
```liquid
Expand All @@ -26,7 +26,7 @@ For this example, assume `site.pages` is an array of content pages for a website
- technology
```

By using `compact` when we create our `site_categories` array, we can remove all the `nil` values in the array.
使用 `compact` 创建 `site_categories` 数组,可以移除所有 `null``undefined` 值。

输入
```liquid
Expand Down
6 changes: 5 additions & 1 deletion src/builtin/filters/array.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isArray, last as arrayLast } from '../../util/underscore'
import { isArray, isNil, last as arrayLast } from '../../util/underscore'
import { toArray } from '../../util/collection'
import { isTruthy } from '../../render/boolean'
import { FilterImpl } from '../../template/filter/filter-impl'
Expand All @@ -24,6 +24,10 @@ export function map<T1, T2> (this: FilterImpl, arr: Scope[], property: string) {
return toArray(arr).map(obj => this.context.getFromScope(obj, property.split('.')))
}

export function compact<T> (this: FilterImpl, arr: T[]) {
return toArray(arr).filter(x => !isNil(x))
}

export function concat<T1, T2> (v: T1[], arg: T2[] | T2): (T1 | T2)[] {
return toArray(v).concat(arg)
}
Expand Down
6 changes: 6 additions & 0 deletions test/integration/builtin/filters/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ describe('filters/array', function () {
return test(tpl, { arr: [a, b, c] }, 'Alice Bob Carol')
})
})
describe('compact', () => {
it('should compact array', function () {
const posts = [{ category: 'foo' }, { category: 'bar' }, { foo: 'bar' }]
return test('{{posts | map: "category" | compact}}', { posts }, 'foo,bar')
})
})
describe('reverse', function () {
it('should support reverse', () => test(
'{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
Expand Down

0 comments on commit f42c217

Please sign in to comment.