DEV Community

Discussion on: Daily Challenge #59 - Snail Sort

Collapse
 
cgty_ky profile image
Cagatay Kaya

It only works where both of the lengths of the arrays are equal. Otherwise, it adds cute 'undefined' in the end. Also, these if checks are there for safety. They may be ugly and repetitive but I did not want the calculate every other case.

const snail = input => {
  let finalResult = [];
  while (
    typeof input != "undefined" &&
    input != null &&
    input.length != null &&
    input.length > 0
  ) {
    const a = input.length;
    //take first line in whole
    if (
      typeof input != "undefined" &&
      input != null &&
      input.length != null &&
      input.length > 0
    ) {
      result = [...input.shift()];
    }

    //take end of each line
    if (
      typeof input != "undefined" &&
      input != null &&
      input.length != null &&
      input.length > 0
    ) {
      for (let index = 0; index < a - 1; index++) {
        const element = input[index].pop();
        result.push(element);
      }
    }
    //take last line in reverse
    if (
      typeof input != "undefined" &&
      input != null &&
      input.length != null &&
      input.length > 0
    ) {
      result = [...result, ...input.pop().reverse()];
    }

    //take start of each middle line
    if (
      typeof input != "undefined" &&
      input != null &&
      input.length != null &&
      input.length > 0
    ) {
      for (let index = a - 3; index > -1; index--) {
        const element = input[index].shift();
        result.push(element);
      }
    }
    //add this loop's result to finalResult
    finalResult = [...finalResult, ...result];
  }
  console.log(finalResult);
};