Last active
July 21, 2016 02:47
-
-
Save russiann/3c71f523324eaa2c66643acdb1923d57 to your computer and use it in GitHub Desktop.
dotNotationPopulate
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
// 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