Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Last active January 11, 2020 21:23
Show Gist options
  • Select an option

  • Save martin-mok/a7f741297314d0b3998c9d69cb46fcdd to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/a7f741297314d0b3998c9d69cb46fcdd to your computer and use it in GitHub Desktop.
freecodecamp: Missing letters

Description

Find the missing letter in the passed letter range and return it. If all letters are present in the range, return undefined.

Tests

tests:
  - text: <code>fearNotLetter("abce")</code> should return "d".
    testString: assert.deepEqual(fearNotLetter('abce'), 'd');
  - text: <code>fearNotLetter("abcdefghjklmno")</code> should return "i".
    testString: assert.deepEqual(fearNotLetter('abcdefghjklmno'), 'i');
  - text: <code>fearNotLetter("stvwx")</code> should return "u".
    testString: assert.deepEqual(fearNotLetter('stvwx'), 'u');
  - text: <code>fearNotLetter("bcdf")</code> should return "e".
    testString: assert.deepEqual(fearNotLetter('bcdf'), 'e');
  - text: <code>fearNotLetter("abcdefghijklmnopqrstuvwxyz")</code> should return undefined.
    testString: assert.isUndefined(fearNotLetter('abcdefghijklmnopqrstuvwxyz'));

Solution

Offical soln:

function fearNotLetter (str) {
  for (var i = str.charCodeAt(0); i <= str.charCodeAt(str.length - 1); i++) {
    var letter = String.fromCharCode(i);
    if (str.indexOf(letter) === -1) {
      return letter;
    }
  }

  return undefined;
}

My soln: first attempt

function fearNotLetter(str) {
  for(let i=1;i<str.length;i++){
    if(str[i].charCodeAt()!==(str[0].charCodeAt()+i)){
      return str[i];
    }
  }
  return undefined;
}

fearNotLetter("abce");

corrected

function fearNotLetter(str) {
  for(let i=1;i<str.length;i++){
    let currCharCode=str[0].charCodeAt()+i;
    if(str[i].charCodeAt()!==currCharCode){
      return String.fromCharCode(currCharCode);
    }
  }
  return undefined;
}

fearNotLetter("abce");

Hugh Winchester soln:

function fearNotLetter(str) {
  var startCode = str.charCodeAt(0);
  for (var i = 0; i < str.length; i++){
    if (str.charCodeAt(i) !== startCode){
      return String.fromCharCode(startCode);
    } else {
      startCode++;
    }
  }
}

Useful Links

Convert character to ASCII code in JavaScript
String.fromCharCode()
String.prototype.charCodeAt()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment