Skip to content

Instantly share code, notes, and snippets.

@russiann
Last active July 21, 2016 02:47
Show Gist options
  • Save russiann/3c71f523324eaa2c66643acdb1923d57 to your computer and use it in GitHub Desktop.
Save russiann/3c71f523324eaa2c66643acdb1923d57 to your computer and use it in GitHub Desktop.
dotNotationPopulate
// Ecmascript 5
function dotNotationPopulate(text) {
function findPopulate(obj, level, index) {
var index = index || 1;
if (level === index || !obj.populate) {
return obj;
}
return findPopulate(obj.populate, level, index + 1);
}
var splitted = text.split('.');
return splitted
.map(function(item, index, list) {
if (index+1 === list.length) {
return { path: item }
} else {
return { path: item, populate: {} }
}
})
.reduce(function(mem, curr, index, list) {
var populate = findPopulate(mem, index);
populate.populate = curr;
return mem;
});
}
// Ecmascript 6
const dotNotationPopulate = (text) => {
const findPopulate = (obj, level, index = 1) => {
if (level === index || !obj.populate)
return obj;
return findPopulate(obj.populate, level, index + 1);
}
const splitted = text.split('.');
return splitted
.map((item, index, list) => {
if (index + 1 === list.length)
return { path: item };
else
return { path: item, populate: {} };
})
.reduce((mem, curr, index) => {
const populate = findPopulate(mem, index);
populate.populate = curr;
return mem;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment