Skip to content

Instantly share code, notes, and snippets.

@sharmaabhinav
Last active November 1, 2017 09:24
Show Gist options
  • Save sharmaabhinav/2e2d30ab56dd385742b13904decb2ea7 to your computer and use it in GitHub Desktop.
Save sharmaabhinav/2e2d30ab56dd385742b13904decb2ea7 to your computer and use it in GitHub Desktop.
function groupBy (collection, func, callback) {
if (typeof func !== 'function') {
callback('please provide a function to group by')
return
}
if (typeof callback !== 'function') {
callback('please provide a function as a callback')
return
}
var callReturnCount = 0
var result = {}
var collectionLength = collection.length
for(var start=0;start <collection.length;start++) {
var collectionItem = collection[start]
processItem(collectionItem)
}
function processItem (item) {
function serverCallback (val) {
if (result[val]){
result[val].push(item)
} else {
result[val] = [item]
}
callReturnCount += 1
if (callReturnCount === collectionLength) {
callback(result)
}
}
func(item, serverCallback)
}
}
let collection = [
{name: 'Abhilash', age: 30, company: 'inmobi'},
{name: 'Abhinav', age: 20, company: 'jiffle'},
{name: 'Rajesh', age: 30, company: 'google'},
{name: 'rahul', age: 20, company: 'jiffle'},
{name: 'akashdeep', age: 30, company: 'google'},
]
groupBy(collection, function(item, cb) {
setTimeout(() => cb(item.name), Math.random() * 500);
}, function(group) {
console.log(group)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment