Created
March 13, 2017 12:54
-
-
Save phgrey/7db9159448295e78fb3747f11808c51b to your computer and use it in GitHub Desktop.
simple domain language for storing conditions in text fields
This file contains hidden or 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
| var _ = require('underscore'), | |
| operators = { | |
| 'in': function(field){ | |
| var values = []; | |
| for(var i = 1; i< arguments.length; i++) | |
| values.push(arguments[i]); | |
| return function(row){ | |
| var test = Array.isArray(row[field]) ? row[field] : [row[field]]; | |
| return _.intersection(test, values).length > 0; | |
| } | |
| }, | |
| 'empty': function(field){ | |
| return function(row){ | |
| return !row[field]; | |
| } | |
| }, | |
| 'and': function(){ | |
| var conditions = []; | |
| for(var i = 0; i< arguments.length; i++) | |
| conditions.push(arguments[i]); | |
| return function(row){ | |
| return !!conditions.every(function(cnd){ | |
| return condition(cnd)(row); | |
| }) | |
| } | |
| }, | |
| 'or' : function(){ | |
| var conditions = []; | |
| for(var i = 0; i< arguments.length; i++) | |
| conditions.push(arguments[i]); | |
| return function(row){ | |
| return !conditions.every(function(cnd){ | |
| return !condition(cnd)(row); | |
| }) | |
| } | |
| }, | |
| 'true': function(){ | |
| return function(){return true;}; | |
| }, | |
| 'false': function(){ | |
| return function(){return false;}; | |
| } | |
| }, | |
| condition = function(conditions){ | |
| return Array.isArray(conditions) && conditions[0] && operators[conditions[0]] | |
| ? operators[conditions[0]].apply(operators, conditions.slice(1)) | |
| : function(){return conditions}; | |
| }; | |
| module.exports = condition; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment