Created
May 24, 2011 16:23
-
-
Save victor-github/989053 to your computer and use it in GitHub Desktop.
Given a string of form field1.field2.field3..., parses it and returns "" if at any point the fields are not defined, or the value of the evaluation if all fields are defined
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
| // usage: ifDefined("field1.field2.field3") - do not specify second argument | |
| ifDefined: function(str_object, prev_eval) { | |
| var i = str_object.indexOf('.'); | |
| if (i === -1) { | |
| return true; | |
| } else { | |
| var first = str_object.substring(0,i), | |
| last = str_object.substring(i+1), | |
| j = last.indexOf('.'), | |
| second = last; | |
| if (j !== -1) { | |
| second = last.substring(0,j); | |
| } | |
| if (typeof prev_eval !== "undefined") { | |
| first = prev_eval; | |
| } | |
| eval_result = eval(first)[second]; | |
| if (typeof eval_result != "undefined") { | |
| var recurse = this.ifDefined(last, eval_result); | |
| if (recurse === true) { | |
| return eval_result; //return last eval if returning from base case | |
| } else { | |
| return recurse; //otherwise, pass the eval back | |
| } | |
| } else { | |
| return ""; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment