Last active
December 11, 2015 20:28
-
-
Save thejhh/4654983 to your computer and use it in GitHub Desktop.
Building equations for multiple systems from JavaScript presentation by calling a function
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
| "use strict"; | |
| /** Query builder */ | |
| function build_query(type, schema) { | |
| // Metadata for builder | |
| var _converters = { | |
| js:{ | |
| or: function(x, y) { return '(' + x + ') || (' + y + ')'; }, | |
| and: function(x, y) { return '(' + x + ') && (' + y + ')'; }, | |
| eq: function(x, y) { return x + ' === ' + y; }, | |
| gt: function(x, y) { return x + ' > ' + y; }, | |
| lt: function(x, y) { return x + ' < ' + y; }, | |
| plus: function(x, y) { return x + ' + ' + y; }, | |
| minus: function(x, y) { return x + ' - ' + y; } | |
| }, | |
| mysql:{ | |
| or: function(x, y) { return '(' + x + ') OR (' + y + ')'; }, | |
| and: function(x, y) { return '(' + x + ') AND (' + y + ')'; }, | |
| eq: function(x, y) { return x + ' = ' + y; }, | |
| gt: function(x, y) { return x + ' > ' + y; }, | |
| lt: function(x, y) { return x + ' < ' + y; }, | |
| plus: function(x, y) { return x + ' + ' + y; }, | |
| minus: function(x, y) { return x + ' - ' + y; } | |
| } | |
| }; | |
| var ops = _converters[type]; | |
| return schema.apply(ops); | |
| } | |
| /** Our Presentation of the Match as pure JavaScript */ | |
| function our_match() { | |
| var id = 'x.id'; | |
| return this.or( | |
| this.eq(id, 10), | |
| this.and( | |
| this.gt(id, 100), | |
| this.lt(id, 200) | |
| ) | |
| ); | |
| } | |
| // Let's build different queries... | |
| console.log('mysql: ' + build_query('mysql', our_match)); | |
| console.log('js: ' + build_query('js', our_match)); | |
| /* | |
| * | |
| * Results: | |
| * | |
| * $ node test.js | |
| * mysql: (x.id = 10) OR ((x.id > 100) AND (x.id < 200)) | |
| * js: (x.id === 10) || ((x.id > 100) && (x.id < 200)) | |
| * | |
| */ | |
| /* EOF */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment