Skip to content

Instantly share code, notes, and snippets.

@antoniopresto
Created December 19, 2017 21:48
Show Gist options
  • Save antoniopresto/c64948f675b4dc52f7c2eda606569059 to your computer and use it in GitHub Desktop.
Save antoniopresto/c64948f675b4dc52f7c2eda606569059 to your computer and use it in GitHub Desktop.
bestMatch.js
// find in objects https://www.npmjs.com/package/q_
function _(o, qs) {
const qa = qs.replace(/\[([0-9]*)]/gim, '.$1').split('.');
return qa.reduce(function(prev, next) {
if (!prev) return undefined;
return prev[next];
}, o);
}
function bestMatch(o, qs) {
return qs.split('.').reduce((prev)=>{
if(prev.found !== undefined) return prev;
const found = _(o, prev.str);
if (found) return {...prev, found};
const str = prev.str.replace(/\.[^.]*$/, '');
return {...prev, str}
}, {str:qs, found:undefined})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment