Stolen Lunch

Description


When you recently visited your little nephew, he told you a sad story: there’s a bully at school who steals his lunch every day, and locks it away in his locker. He also leaves a note with a strange, coded message. Your nephew gave you one of the notes in hope that you can decipher it for him. And you did: it looks like all the digits in it are replaced with letters and vice versa. Digit 0 is replaced with 'a', 1 is replaced with 'b' and so on, with digit 9 replaced by 'j'.

The note is different every day, so you decide to write a function that will decipher it for your nephew on an ongoing basis.

Example

For note = "you'll n4v4r 6u4ss 8t: cdja", the output should be stolenLunch(note) = "you'll never guess it: 2390".

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] string note

    A string consisting of lowercase English letters, digits, punctuation marks and whitespace characters (' ').

    Guaranteed constraints:
    0 ≤ note.length ≤ 500.

  • [output] string

    • The deciphered note.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
function stolenLunch(note) {
  return note.replace(/\d|[a-j]/g, function (char) {
    if (char >= "a" && char <= "j") {
      return String.fromCharCode(char.charCodeAt(0) - 'a'.charCodeAt(0) + '0'.charCodeAt(0));
    } else {
      return String.fromCharCode(char.charCodeAt(0) - '0'.charCodeAt(0) + 'a'.charCodeAt(0));
    }
  });
}