Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lsmith/136080 to your computer and use it in GitHub Desktop.
Save lsmith/136080 to your computer and use it in GitHub Desktop.
// Function to convert the schema's fields into walk paths
var buildPath = function (needle) {
var path = null, keys = [], i = 0;
if (needle) {
// Strip the ["string keys"] and [1] array indexes
needle = needle.
replace(/\[(['"])(.*?)\1\]/g,
function (x,$1,$2) {
keys[i]=$2;
return '.@'+(i++);
}).
replace(/\[(\d+)\]/g,
function (x,$1) {
keys[i]=parseInt($1,10)|0;
return '.@'+(i++);
}).replace(/^\./,''); // remove leading dot
// If the cleaned needle contains invalid characters, the
// path is invalid
if (!/[^\w\.\$@]/.test(needle)) {
path = needle.split('.');
for (i=path.length-1; i >= 0; --i) {
if (path[i].charAt(0) === '@') {
path[i] = keys[parseInt(path[i].substr(1),10)];
}
}
} else {
YAHOO.log("Invalid locator: " + needle, "error", this.toString());
}
}
return path;
};
// Function to walk a path and return the pot of gold
var walkPath = function (path, origin) {
var v = origin || window,
i = 0,
len = path.length;
for (; i < len && v; ++i) {
v = v[path[i]];
}
return v;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment