Created
May 25, 2015 21:55
-
-
Save slezica/53766d2f389a09d1aebb to your computer and use it in GitHub Desktop.
Simple coffee validation
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
kindof = (x) -> | |
if x? then x.constructor else x | |
validateWithFunction = (object, func) -> | |
true_or_reason = func(object) | |
if true_or_reason is true | |
{ valid: true } | |
else | |
{ valid: false, reason: true_or_reason } | |
validateWithObject = (object, schema) -> | |
result = {} | |
result[key] = validate(object[key], schema[key]) for key of schema | |
result | |
validate = (object, desc, debug = true) -> | |
result = switch kindof(desc) | |
when Object then validateWithObject(object, desc) | |
when Function then validateWithFunction(object, desc) | |
if debug # these are non-enumerable | |
Object.defineProperty(result, '$object', value: object) | |
Object.defineProperty(result, '$desc', value: desc) | |
return result | |
is_2 = (x) -> | |
x is 2 or "x is not 2" | |
is_person = (person) -> | |
validate person, | |
name: (name) -> | |
switch | |
when kindof(name) isnt String then "Not a string" | |
when name.length is 0 then "Name is empty" | |
else true | |
age: (age) -> | |
switch | |
when kindof(age) isnt Number then "Not a number" | |
when age < 1 then "Must be >= 1" | |
else true | |
test = (object, desc) -> | |
log object | |
# log desc.name | |
log validate(object, desc) | |
log '-' | |
# test 1, is_2 | |
test {}, is_person | |
test { age: 3 }, is_person |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment