Skip to content

Instantly share code, notes, and snippets.

@darkcris1
Last active March 29, 2023 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkcris1/d919288083de5fb078df744958151e94 to your computer and use it in GitHub Desktop.
Save darkcris1/d919288083de5fb078df744958151e94 to your computer and use it in GitHub Desktop.
Range Extraction | Codewars
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"
@pasikonik
Copy link

pasikonik commented Mar 20, 2023

It doesn't work for end of array within range. Eg.
[1,2,5,6,9,10]

@younes-benniz
Copy link

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