Created
April 8, 2019 14:47
-
-
Save patarapolw/3f7a82b762081564f7c13fb968099f36 to your computer and use it in GitHub Desktop.
convert mongo query to filter function
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
export function mongoFilter(x: any, cond: any): boolean { | |
return Object.keys(cond).every((k) => { | |
if (k === "$or") { | |
return (cond[k] as any[]).some((c0) => mongoFilter(x, c0)); | |
} else if (k === "$and") { | |
return (cond[k] as any[]).every((c0) => mongoFilter(x, c0)); | |
} else { | |
let dotIndex = k.indexOf("."); | |
while (dotIndex !== -1) { | |
x = x[k.slice(0, dotIndex)]; | |
k = k.slice(dotIndex + 1); | |
dotIndex = k.indexOf("."); | |
} | |
return mongoCond(x[k], cond[k]); | |
} | |
}); | |
} | |
function mongoCond(v: any, condk: any): boolean { | |
if (typeof condk === "object") { | |
for (const k of Object.keys(condk)) { | |
return op_(v, k, condk[k]); | |
} | |
} | |
return v === condk; | |
} | |
function op_(a: string, o: string, v: any): boolean { | |
const _op = { | |
$regex: (v0: any) => new RegExp(v0.toString()).test(a), | |
$stringContains: (v0: any) => a.indexOf(v0.toString()) !== -1, | |
$gt: (v0: any) => a > v0, | |
$gte: (v0: any) => a >= v0, | |
$lt: (v0: any) => a < v0, | |
$lte: (v0: any) => a <= v0 | |
}; | |
if (typeof (_op as any)[o] === "function") { | |
if (Array.isArray(v)) { | |
return v.every((v0) => (_op as any)[o](v0)); | |
} else { | |
return (_op as any)[o](v); | |
} | |
} else { | |
console.log(o); | |
return a === v; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment