TypeScript | JavaScript Algorithms | Staircase solution. - kyg news .

TypeScript Coding

6 Views

        

// Staircase - HackerHank

const BREAK_CHAR = '\n';
const HASH_CHAR = '#';
const WHITESPACE_CHAR = ' ';

type StairOptions = {
  length: number;
  symbolTotal: number;
  isLeft?: boolean; 
}

/**
 * Complete the staircase function in the editor below.
 *
 * Staircase has the following parameter(s):
 *  int n: an integer
 */
function isNotBetweenLength(lnegth: number): boolean {
  return !(lnegth >= 1 && lnegth <= 100);
}

function staircase(n: number): string {
  const isNotContraintsPass = isNotBetweenLength(n);

  if (isNotContraintsPass) {
    // Error: "Invalid input/length".
    return ""; 
  }

  const arr = Array.from({ length: n }, (_, i) => i + 1);

  function stairChar({ length, symbolTotal, isLeft }: StairOptions): string {
    let str: string = '';

    const LENGTH = length;

    /*
    for (let i = 0; i < LENGTH; i++) {
      const diff = LENGTH - symbolTotal;
      const betweenHashChar = isLeft ? (i < symbolTotal) : (i >= diff);
  
      if (betweenHashChar) {
        str += HASH_CHAR;
        continue;
      }
      str += WHITESPACE_CHAR;
    } */

    let i: number = 0;

    while (i < LENGTH) {
      const diff = LENGTH - symbolTotal;

      const isBetweenOrDirection = isLeft ? (i < symbolTotal) : (i >= diff);

      if (isBetweenOrDirection) {
        str += HASH_CHAR;
        //continue;
      } else {
        str += WHITESPACE_CHAR;
      }

      i++;
    }

    return str;
  }
 
  const stairArr = arr.map((v) => {
    return stairChar({
      length: n,
      symbolTotal: v,
      isLeft: false,
    });
  });

  // Join/includes "\n"
  return stairArr.join(BREAK_CHAR);
}

// console.time('Stair')

const stair = staircase(6);

// console.timeEnd('Stair')

console.log(stair)