mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-15 04:10:40 -07:00
feat: compact filter
This commit is contained in:
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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: "" }}',
|
||||
|
||||
Reference in New Issue
Block a user