Skip to content

Instantly share code, notes, and snippets.

@jamischarles
Last active January 8, 2020 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamischarles/d6f61122312a6a8880428fa3d12bc750 to your computer and use it in GitHub Desktop.
Save jamischarles/d6f61122312a6a8880428fa3d12bc750 to your computer and use it in GitHub Desktop.
Rebuilding simple version of _.get()
function get(base, pathQuery, returnOnUndefinedValue) {
var pathArr = pathQuery.split('.');
var currentVal = base;
for (var i=0; i<pathArr.length; i++) {
var key = pathArr[i];
currentVal = currentVal[key];
if (!currentVal) {
return returnOnUndefinedValue ;
}
}
return currentVal;
}
// FIXME: check for window vs global myself?
// and make that the base?
// logs the part of the path that's valid... great for finding where the path goes bad...
function findValidPath(pathQuery) {
var pathArr = pathQuery.split('.')
var lastValidPath = eval(pathArr[0]) // TOOD: consider using window / global as base here instead of using eval...
// start at 1 bc we already have 0
for (var i = 1; i < pathArr.length; i++) {
var key = pathArr[i]
var nextPath = lastValidPath[key]
console.log('key', key)
console.log("lastValidPath", lastValidPath)
console.log('nextPath', nextPath)
if (!nextPath) {
// return path and value
console.log('i', i)
return {
validPath: pathArr.slice(0, i).join("."),
value: lastValidPath
}
} else {
lastValidPath = nextPath
}
}
// Whole path, bc whole path is valid...
return {
validPath: pathArr.slice(0, i).join("."),
value: lastValidPath
}
}
// test cases
var test1 = {
a: {
b: 'valid'
}
}
console.log("TEST CASE 1", findValidPath('test1.a.b')) // whole path is valid
console.log("TEST CASE 2", findValidPath('test1.a.a')) // partially valid path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment