Created
September 14, 2017 06:14
-
-
Save ssddi456/430b661cc73deecbffd70f4764aacd97 to your computer and use it in GitHub Desktop.
make number sequence to range sequence 1, 2, 3, 5, 6, 8 => 1-3, 5-6, 8
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 last(nums) { | |
return nums[nums.length - 1]; | |
} | |
function makeRange(nums) { | |
return nums.slice().sort(function (a, b) { return a - b; }) | |
.reduce(function (segs, current) { | |
var lastSeg = last(segs); | |
var currentSeg = lastSeg || []; | |
if (!lastSeg) { | |
segs.push(currentSeg); | |
} | |
var lastNumber = last(currentSeg); | |
if (lastNumber === undefined) { | |
currentSeg.push(current); | |
} | |
else if (lastNumber + 1 === current) { | |
if (currentSeg.length === 1) { | |
currentSeg.push(current); | |
} | |
else { | |
currentSeg[1] = current; | |
} | |
} | |
else { | |
segs.push([current]); | |
} | |
return segs; | |
}, []) | |
.map(function (a) { return a.join('-'); }) | |
.join(','); | |
} | |
makeRange([1, 2, 3, 5, 6, 7, 9]); | |
makeRange([1, 2, 3, 6, 8]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment