Last active
March 29, 2023 22:24
-
-
Save darkcris1/d919288083de5fb078df744958151e94 to your computer and use it in GitHub Desktop.
Range Extraction | Codewars
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 solution(list) { | |
const result = [] | |
let str = [] | |
for (let i = 0; i < list.length; i++) { | |
if (list[i + 1] === list[i] + 1) { | |
str.push(list[i]) | |
} else { | |
if (str.length < 2) { | |
result.push(...str, list[i]) | |
} else { | |
result.push(str[0] + '-' + list[i]) | |
} | |
str = [] | |
} | |
} | |
return result.join() | |
} | |
console.log(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])); | |
// "-6,-3-1,3-5,7-11,14,15,17-20" |
function solution(list){
let result = [];
let tempArr = [];
for (let num of list) {
let followingItem = list[list.indexOf(num) + 1];
if (num + 1 === followingItem) {
tempArr.push(num, followingItem)
} else {
if (tempArr.length > 3) {
result.push(`${tempArr[0]}-${tempArr[tempArr.length - 1]}`)
} else if (tempArr.length === 2) {
result.push(...tempArr);
} else {
result.push(num)
}
tempArr = []
}
}
return result.join();
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It doesn't work for end of array within range. Eg.
[1,2,5,6,9,10]