Last active
October 8, 2018 18:17
-
-
Save huruji/e554e4b9f16e310b44c46458013daf68 to your computer and use it in GitHub Desktop.
A simple fluent validator using Proxy
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
var proxyContext = function(ctx) { | |
return new Proxy(ctx, { | |
get(obj, prop) { | |
if (prop in obj) { | |
return obj[prop]; | |
} | |
const newCtx = proxyContext(ctx.clone()); | |
if (prop in rules) { | |
let re = newCtx.addRule(rules[prop]); | |
return re; | |
} | |
} | |
}) | |
} | |
class Context { | |
constructor(rules = []) { | |
this.rules = rules; | |
} | |
addRule(rule) { | |
return (...args) => { | |
this.rules.push(rule.apply(this, args)); | |
return this; | |
} | |
} | |
test (value) { | |
let result = true; | |
for(let i = 0; i < this.rules.length; i++) { | |
result = this.rules[i](value); | |
if(!result) return result; | |
} | |
return result; | |
} | |
clone() { | |
return new Context(this.rules.slice()); | |
} | |
} | |
var a = new Context(); | |
var validation = () => { | |
return proxyContext(a); | |
} | |
var rules = { | |
exact (target) { | |
return value => value === target; | |
}, | |
equal (target) { | |
return value => value == target; | |
}, | |
minLength (len) { | |
return value => value.length >= len | |
}, | |
startWith(target) { | |
return value => value[0] === target | |
} | |
} | |
var result2 = validation().minLength(6).startWith('h').test('huruji'); | |
console.log(result2); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment