Last active
November 1, 2017 09:24
-
-
Save sharmaabhinav/2e2d30ab56dd385742b13904decb2ea7 to your computer and use it in GitHub Desktop.
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
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