Skip to content

Commit

Permalink
feat: where filter, working on #118
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Apr 1, 2019
1 parent a084183 commit daa0b57
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/builtin/filters/array.ts
Original file line number Diff line number Diff line change
@@ -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),
Expand All @@ -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 changes: 24 additions & 0 deletions test/integration/builtin/filters/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
`)
})
})
})
11 changes: 10 additions & 1 deletion test/stub/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit daa0b57

Please sign in to comment.