Comparing a user supplied string to a string on the data object
Closed this issue · 5 comments
I'm trying to implement a way to filter out objects based on the user supplied string. I wanted to string match using a fuzzy match algorithm, but when defining a custom function:
fuzzy(inputString, matchString) {
// return boolean
}
and setting the filter expression to this (example data object: { name: 'John K', age: 18 }
):
fuzzy(name, 'John')
doesn't pass 'John' to the custom function. Is there a way to do this?
Hey Talat!
Sorry for the late reply! The problem with your code is that you use single quotes – by looking at the Readme, you can see that strings in Filtrex use double quotes while single quotes are reserved for symbols. In your case, all four of these are identical:
fuzzy(name, John)
fuzzy('name', John)
fuzzy(name, 'John')
fuzzy('name', 'John')
What you actually want is:
fuzzy(name, "John")
You might also be interested in operator overloading which will be added in Filtrex v3. You can already use it, as v3 has a release candidate on NPM.
import { compileExpression } from "filtrex";
const options = {
operators: {
'~=': function fuzzy(a, b) { return a.toLowerCase().includes(b.toLowerCase()) }
}
};
const expr = `name ~= "john"`;
const f = compileExpression(expr, options);
f({ name: "John Doe"}) // true
f({ name: "Jane Smith"}) // false
Thank you, this was very helpful. I'll definitely check v3 out.
Update: I've finally published v3 as a stable release. Therefore you don't have to worry about release candidates and the like :)