JEWEL THIEF KATA

https://www.codewars.com/kata/jewel-thief/train/javascript

by Artem

JavaScript

const crack = safe => {
  const LAST_ITERATION = 2;
  const SPIN_DIRECTION = {
    LEFT: 'L',
    RIGHT: 'R',
  };

  const generateCipherPair = function*(combination) {
    for (let spinDirection = 0; spinDirection < Object.keys(SPIN_DIRECTION).length; spinDirection++) {
      const dir = SPIN_DIRECTION[Object.keys(SPIN_DIRECTION)[spinDirection]];
      for (let num = 0; num < 100; num++) {
        const numPart = num < 10 ? `0${num}` : `${num}`;
        let comb = (combination + dir + numPart);
        yield comb;
      }
    }
  };

  const generateCombination = leading => {
    let next;
    const combination = !leading ? '' : leading + '-';

    const iterationCount = combination.split(/(-)/).filter(el => el === '-').length;
    const cipherPair = generateCipherPair(combination);

    do {
      next = cipherPair.next();

      let val = next.value;
      let successCode = val.replace(/\w{3}/g, 'click');

      if (safe.unlock(val) === successCode) {
        return iterationCount < LAST_ITERATION ? generateCombination(val) : safe.open();
      }
    } while (!next.done)
  }

  return generateCombination();
}