Last active
August 29, 2015 14:27
-
-
Save dtipson/546eff62f3108e2782ad to your computer and use it in GitHub Desktop.
all sorts of ways of checking two values against each other
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
/*use the type of a test value to compare two values in different ways*/ | |
var multicompare = _.curry(function(test,what){ | |
var splittest; | |
if(typeof test === "string"){ | |
if(test.indexOf('this.')===0){ | |
what = this; | |
test = test.replace('this.',''); | |
} | |
if(test.indexOf('.{')>0){ | |
console.log('object string'); | |
splittest = test.split('.{'); | |
what = _.get(what,splittest[0]); | |
try{ | |
test = JSON.parse("{"+splittest[1]); | |
}catch(e){ | |
test = null; | |
} | |
} | |
} | |
return !_.isError(what) && ( | |
((typeof test === "number" || typeof test==="boolean") && test===what) || | |
(_.isPlainObject(test) && _.matches(test)(what)) || | |
(typeof test === "string" && !!_.get(what,test)) || | |
(typeof test === "function" && test(what)) | |
); | |
}); | |
// if what is type Error, fail | |
// if test is type number or boolean, exact equality comparison | |
// if test is a plain object, use lodash's matches to compare to what | |
// if test is function that returns true or false, run it with what as the argument | |
// if test is a string, treat it as a tokenized path and return true if the value | |
// at that path exists and is truthy | |
// Also for string tests, consider any strings that start with "this." | |
// to refer to the contextual this ignoring "what" | |
// Also for string tests, allow a a string like "path.path.{prop:value}", | |
// which looks into the path before '{"prop":value}'', parses that object | |
// syntax into a real object, | |
// and passes it to _.matches |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment