Created
July 5, 2018 18:48
-
-
Save davidcostadev/45d314259a35c16ca79b31f323e2c35b to your computer and use it in GitHub Desktop.
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
| console.clear() | |
| const l = console.log | |
| const opAND = (fields) => { | |
| return Object.keys(fields) | |
| .map(field => opLogic(field, fields[field])) | |
| .join(' AND ') | |
| } | |
| const opOR = (fields) => { | |
| return Object.keys(fields) | |
| .map(field => opLogic(field, fields[field])) | |
| .join(' OR ') | |
| } | |
| const opEQ = (field, value) => `${field} = ${value}` | |
| const opNE = (field, value) => `${field} != ${value}` | |
| const operations = { | |
| 'AND': opAND, | |
| 'OR': opOR, | |
| 'EQ': opEQ, | |
| 'NE': opNE, | |
| } | |
| const opLogic = (field, value) => { | |
| if (typeof value === 'string') { | |
| return opEQ(field, value) | |
| } | |
| return Object.keys(value) | |
| .map(op => operations[op](field, value[op])) | |
| } | |
| const findOperation = (op, value) => { | |
| if (typeof operations[op] === 'undefined') { | |
| return opLogic(op, value) // | |
| } | |
| return operations[op](value) | |
| } | |
| const where = (attrs) => { | |
| const logic = Object.keys(attrs) | |
| .map(att => findOperation(att, attrs[att])) | |
| if (logic.length === 1) { | |
| return `WHERE \n\t${logic[0]}` | |
| } | |
| return `WHERE \n\t(${logic.join(")\n AND \n\t(")})\n` | |
| } | |
| console.log(where({ | |
| ['AND'] : { | |
| name: 'David', | |
| email: { | |
| ['NE']: 'david@costa.com' | |
| } | |
| }, | |
| ['OR'] : { | |
| name: 'David', | |
| email: 'david@costa.com' | |
| }, | |
| name: 'Legal', | |
| idade: { | |
| ['NE']: 3 | |
| } | |
| })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment