v1
- by nikkypizza 7/27/202200
Setup HTML - click to add setup HTML
disable setup JavaScript
Setup JavaScript
const getIntervalsMySolution = (input) => {
  if (!Array.isArray(input)) return '';

  const result = [];
  const arrOfArrs = [[]];

  input.sort((a, b) => a - b).forEach((number, i, arr) => {
    arrOfArrs[arrOfArrs.length - 1].push(number);
    if (number !== arr[i + 1] - 1) {
      arrOfArrs.push([]);
    }
  });

  arrOfArrs.forEach((arr) => {
    if (arr.length <= 2) result.push(arr.join(', '));
    if (arr.length > 2) result.push(`${arr[0]}-${arr[arr.length -1]}`);
  });

  return result.join(', ');
}

const getIntervalsHisSolution = (input) => {
  if (!Array.isArray(input)) return '';

  const result = [];
  let tempArr = [];

  input.sort((a, b) => a - b).forEach((num, i, arr) => {
    tempArr.push(num);

    if (num !== arr[i + 1] - 1) {
      if (tempArr.length <= 2) result.push(tempArr.join(", "));
      else result.push(`${tempArr[0]}-${tempArr[tempArr.length - 1]}`);
      tempArr = [];
    }
  })
  
  return result.join(', ');
}

const getIntervals = (arr) => {
  if (!Array.isArray(arr)) return '';

  arr.sort((a, b) => a - b);

  let temp = [];
  const result = [];
  
  for (let i = 0; i < arr.length; i++) {
    temp.push(arr[i]);

    if (arr[i] + 1 !== arr[i + 1]) {
      temp.length > 2
        ? result.push(`${temp[0]}-${temp[temp.length - 1]}`)
        : result.push(...temp);

      temp = [];
    }
  }
  return result.join(", ");
};


///////

const test = (fn) => {
	fn([-77, -78, -79, -10, -40, 0, -1, -2]);
	fn([1,3,2,14,6,11,5,13,12]);
};
delete caserun single casemove downdrag and drop case


ready



test(getIntervalsMySolution)
delete caserun single casemove upmove downdrag and drop case


ready



test(getIntervalsHisSolution)
delete caserun single casemove updrag and drop case


ready



test(getIntervals)
Test Case - click to add another test case
Teardown JS - click to add teardown JavaScript
Output (DOM) - click to monitor output (DOM) while test is running
RUN