Created
February 9, 2018 23:35
-
-
Save pokatomnik/ed35ce550fa5522ba1fe029343cb8529 to your computer and use it in GitHub Desktop.
Yandex interview tasks
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
// [1, 3, 5, 7, 8, 11, 12, 13, 20] -> 1,3,5,7-8,11-13,20 | |
function short(arr) { | |
var sorted = arr.sort(function (a, b) { | |
if (a < b) { return -1; } | |
else if (a > b) { return 1; } | |
else { return 0; } | |
}); | |
function add(res, newValue) { | |
var last = res[res.length-1]; | |
if (!last) { | |
res.push([newValue]); | |
return; | |
} | |
var [firstItem, lastItem] = last; | |
if (firstItem && lastItem) { | |
if (lastItem+1 === newValue) { | |
last[last.length-1] = newValue; | |
} else { | |
res.push([newValue]); | |
} | |
} else if (firstItem) { | |
if (firstItem + 1 === newValue) { | |
last.push(newValue); | |
} else { | |
res.push([newValue]); | |
} | |
} else { | |
last.push(newValue); | |
} | |
} | |
return sorted | |
.reduce(function (res, currentItem) { | |
add(res, currentItem); | |
return res; | |
}, []) | |
.map(function (minMax) { | |
return minMax.join('-'); | |
}) | |
.join(','); | |
} | |
short([1, 3, 5, 7, 8, 11, 12, 13, 20]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment