HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Find the missing letter in sequence

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
findthesequencemissingletter

Problem

The challenge was to find the missing letter in an array in alphabetical order.


Find the missing letter in the passed letter range and return it.


If all letters are present in the range, return undefined.

My solution was this:

function fearNotLetter(str) {
  var letters = str.split('');
  var codes = [];
  var missing = 0;
  var start = 0 , next = 0 , c = 0;
  for(var i= 0; i < letters.length; i++){
    var charcode = letters[i].toString();
    codes.push(charcode.charCodeAt());
  }
  for(var j = 1; j < codes.length; j++){
    start = codes[j] -1;
    if(codes.indexOf(start) === -1){
      missing += start;
    }

  }
  if(missing === 0){
    return undefined
  }else {
    return String.fromCharCode(missing);
  }
}


I am wondering whether I have followed some bad practices or used dry code which might cause problems in a later use. Thanks in advance.

Solution

In general, you don't need to split the string and then process the array. Simply you must start from the first letter and store its charcode and then process the next later and check with the incremented charcode. If there is a difference than just break.

function f(str) {
    if (str && 0 < str.length) {
        var desCharCode = str.charCodeAt(0);
        for (var i = 1; i < str.length; ++i) {
            ++desCharCode;
            if (str.charCodeAt(i) != desCharCode) {
                return String.fromCharCode(desCharCode);
            }
        }
    }

    return undefined;
}

Code Snippets

function f(str) {
    if (str && 0 < str.length) {
        var desCharCode = str.charCodeAt(0);
        for (var i = 1; i < str.length; ++i) {
            ++desCharCode;
            if (str.charCodeAt(i) != desCharCode) {
                return String.fromCharCode(desCharCode);
            }
        }
    }

    return undefined;
}

Context

StackExchange Code Review Q#160301, answer score: 4

Revisions (0)

No revisions yet.