Created
October 2, 2015 18:02
-
-
Save aaronpk/05519081d5b5aa3ed00c 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
/* | |
Array.findRanges | |
Turns this: | |
["a","a","a","b","b","c","c","c","c","c","a","a","c"] | |
into this: | |
{ | |
"a":[ | |
{ | |
"from":0, | |
"to":2 | |
}, | |
{ | |
"from":10, | |
"to":11 | |
} | |
], | |
"b":[ | |
{ | |
"from":3, | |
"to":4 | |
} | |
], | |
"c":[ | |
{ | |
"from":5, | |
"to":9 | |
}, | |
{ | |
"from":12, | |
"to":12 | |
} | |
] | |
} | |
*/ | |
Array.prototype.findRanges = function() { | |
var buckets = {}; | |
for(var i = 0; i < this.length; i++) { | |
if(!(this[i] in buckets)) { | |
buckets[this[i]] = [{ | |
from: i, | |
to: i | |
}] | |
} else { | |
var last = buckets[this[i]][ buckets[this[i]].length-1 ]; | |
if(i == last.to + 1) { | |
last.to = i; | |
} else { | |
buckets[this[i]].push({ | |
from: i, | |
to: i | |
}) | |
} | |
} | |
} | |
return buckets; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment