Skip to content

Instantly share code, notes, and snippets.

@bmeck
Forked from getify/gist:8109596
Last active January 1, 2016 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmeck/8110130 to your computer and use it in GitHub Desktop.
Save bmeck/8110130 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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