Skip to content

Commit 3019075

Browse files
committed
fix: functions filter and if wrongly filtering on empty strings
1 parent 511d3d1 commit 3019075

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/functions.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ export const functions: FunctionBuildersMap = {
8181
filter: <T>(predicate: JSONQuery[]) => {
8282
const _predicate = compile(predicate)
8383

84-
return (data: T[]) => data.filter(_predicate)
84+
return (data: T[]) => data.filter((item) => truthy(_predicate(item)))
8585
},
8686

8787
sort: <T>(path: JSONQueryProperty = ['get'], direction?: 'asc' | 'desc') => {
@@ -209,7 +209,7 @@ export const functions: FunctionBuildersMap = {
209209
const _valueIfTrue = compile(valueIfTrue)
210210
const _valueIfFalse = compile(valueIfFalse)
211211

212-
return (data: unknown) => (_condition(data) ? _valueIfTrue(data) : _valueIfFalse(data))
212+
return (data: unknown) => (truthy(_condition(data)) ? _valueIfTrue(data) : _valueIfFalse(data))
213213
},
214214
in: (path: string, values: JSONQuery) => {
215215
const getter = compile(path)
@@ -248,3 +248,5 @@ export const functions: FunctionBuildersMap = {
248248
return Number(`${num}e${-digits}`)
249249
})
250250
}
251+
252+
const truthy = (x: unknown) => x !== null && x !== 0 && x !== false

test-suite/compile.test.json

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,13 @@
228228
"query": ["filter", ["get"]],
229229
"output": [-1, 1, 2, 3]
230230
},
231+
{
232+
"category": "filter",
233+
"description": "should filter an array with strings",
234+
"input": ["hello", "", "world", " "],
235+
"query": ["filter", ["get"]],
236+
"output": ["hello", "", "world", " "]
237+
},
231238

232239
{
233240
"category": "sort",
@@ -983,7 +990,7 @@
983990
"description": "should calculate if (7)",
984991
"input": null,
985992
"query": ["if", "", true, false],
986-
"output": false
993+
"output": true
987994
},
988995
{
989996
"category": "if",

0 commit comments

Comments
 (0)