Jun Yang
2019-04-02 00:46:32 +08:00
parent a084183246
commit daa0b574fc
3 changed files with 38 additions and 1 deletions
+4
View File
@@ -1,4 +1,5 @@
import { last } from '../../util/underscore'
import { isTruthy } from '../../render/syntax'
export default {
'join': (v: any[], arg: string) => v.join(arg === undefined ? ' ' : arg),
@@ -20,5 +21,8 @@ export default {
u[String(val)] = true
return true
})
},
'where': function<T> (arr: T[], property: string, value?: any): T[] {
return arr.filter(obj => value === undefined ? isTruthy(obj[property]) : obj[property] === value)
}
}
+24
View File
@@ -64,4 +64,28 @@ describe('filters/array', function () {
return test('{{"" | uniq | join: ","}}', '')
})
})
describe('where', function () {
it('should support filter by property value', function () {
return test(`{% assign kitchen_products = products | where: "type", "kitchen" %}
Kitchen products:
{% for product in kitchen_products -%}
- {{ product.title }}
{% endfor %}`, `
Kitchen products:
- Spatula
- Garlic press
`)
})
it('should support filter truthy property', function () {
return test(`{% assign available_products = products | where: "available" %}
Available products:
{% for product in available_products -%}
- {{ product.title }}
{% endfor %}`, `
Available products:
- Coffee mug
- Boring sneakers
`)
})
})
})
+10 -1
View File
@@ -9,7 +9,16 @@ export const ctx = {
arr: [-2, 'a'],
obj: { foo: 'bar' },
func: function () {},
posts: [{ category: 'foo' }, { category: 'bar' }]
posts: [{ category: 'foo' }, { category: 'bar' }],
products: [
{title: 'Vacuum', type: 'living room'},
{title: 'Spatula', type: 'kitchen'},
{title: 'Television', type: 'living room'},
{title: 'Garlic press', type: 'kitchen'},
{title: 'Coffee mug', available: true},
{title: 'Limited edition sneakers', available: false},
{title: 'Boring sneakers', available: true}
]
}
export async function test (src: string, dst: string) {