-
-
Save bmeck/8110130 to your computer and use it in GitHub Desktop.
This file contains 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 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 []; | |
} |
This file contains 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
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 ] ] |
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
Cool!
FYI: I don't think you even need the
if (arr.length) { .. }
wrapping condition, asreduce()
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.