Skip to content

Instantly share code, notes, and snippets.

@bmeck

bmeck/gist:8110130

Forked from getify/gist:8109596
Last active Jan 1, 2016
Embed
What would you like to do?
function collectLikes(arr) {
arr = Array.prototype.slice.call(arr);
if (arr.length) {
// our current type
var current_type = typeof arr[0];
// our start of type
var left = 0;
return arr.reduce(function (current, value, index, arr) {
// only need to do work if type is different
if (typeof value !== current_type) {
current.push(arr.slice(left, index));
left = index;
current_type = typeof value;
}
// cleanup at end of array for dangling items
if (index === arr.length - 1) {
current.push(arr.slice(left));
}
return current;
}, []);
}
return [];
}
console.log("[ ]",collectLikes([]));
// [ ]
// [ ]
console.log("[ 1 ]",collectLikes([1]));
// [ 1 ]
// [ [ 1 ] ]
console.log("[ 1, 2, 3 ]",collectLikes([1,2,3]));
// [ 1, 2, 3 ]
// [ [ 1, 2, 3 ] ]
console.log("[ 1, 2, '3', '4', '5', 6, true ]",collectLikes([1,2,'3','4','5',6,true]));
// [ 1, 2, '3', '4', '5', 6, true ]
// [ [ 1, 2 ], [ '3', '4', '5' ], [ 6 ], [ true ] ]
console.log("[ 1, '2', 3, true, false, null ]",collectLikes([1,'2',3,true,false,null]));
// [ 1, '2', 3, true, false, null ]
// [ [ 1 ], [ '2' ], [ 3 ], [ true, false ], [ null ] ]
@getify

This comment has been minimized.

Copy link

@getify getify commented Dec 24, 2013

Cool!

FYI: I don't think you even need the if (arr.length) { .. } wrapping condition, as reduce() should return the empty [] in the base case that it doesn't need to reduce at all. Tested without and it seems to work for my test cases.

@bmeck

This comment has been minimized.

Copy link
Owner Author

@bmeck bmeck commented Dec 24, 2013

I just did not want to do a arr[0] for the original type if the array is too small, this can cause odd effects since you are changing from a raw array to a object in the VM, unsure if it can affect JIT so I just guard against it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.