Skip to content

Instantly share code, notes, and snippets.

@davidcostadev
Created July 5, 2018 18:48
Show Gist options
  • Select an option

  • Save davidcostadev/45d314259a35c16ca79b31f323e2c35b to your computer and use it in GitHub Desktop.

Select an option

Save davidcostadev/45d314259a35c16ca79b31f323e2c35b to your computer and use it in GitHub Desktop.
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