Last active
December 15, 2017 22:15
-
-
Save petermoresi/2094dcbdca11ad6641d70d293270aa6c to your computer and use it in GitHub Desktop.
Filter data with formula
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import filter function from formula library | |
var { filter } = require('formula'); | |
// test data | |
let data = [ | |
{ id: 1, name: 'Joe', data: [1, 2, 3] }, | |
{ id: 2, name: 'Joe', data: [10, 20, 30], created: new Date() }, | |
{ age: 1 }, | |
{ age: 10 }, | |
{ age: 100 }, | |
]; | |
// exec query and print results | |
function exec(...query) { | |
var filteredRecords = filter(data, ...query); | |
console.log("=========================================") | |
console.log('Query = ', query); | |
console.log('FilteredRecords =', JSON.stringify(filteredRecords, null, 4)); | |
}; | |
// simple rules | |
exec('age > 10'); | |
exec('name = "Joe"'); | |
// multiple rules requires all rules be true. | |
exec('age < 10', 'age > 0'); | |
// check if field is date | |
exec('isDate(created)'); | |
// any rule is true | |
exec('or( and( age < 5, age > 0), age > 20 )'); | |
// check if field is empty | |
exec('isEmpty( age )'); | |
// check if field is empty | |
exec('not(isEmpty( age ))'); | |
// check if data has 1 or more items or characters | |
exec('len( if( data, data, "" ) ) > 0'); | |
// all rules must be true | |
exec('and( name = "Joe", isEmpty(created) )'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment