Skip to content

Instantly share code, notes, and snippets.

@tparveen
Created June 12, 2018 18:17
Show Gist options
  • Save tparveen/c0a25a8751b1c5eb544dcf23744a663e to your computer and use it in GitHub Desktop.
Save tparveen/c0a25a8751b1c5eb544dcf23744a663e to your computer and use it in GitHub Desktop.
W1-D2-Cracking the Code review
/*
https://github.com/rich-at-thinkful/ft-curric-gists/blob/master/fundamentals/function-drills-2.md#cracking-the-code)
A code has been invented which replaces each character in a sentence with a
five letter word. The first letter of each encoded word determines which of the remaining
four characters contains the decoded character according to this table:
First letter Character number
a 2
b 3
c 4
d 5
So for example, the encoded word 'cycle' would be decoded to the character 'l'.
This is because the first letter is a 'c', so you look for the fourth character, which is 'l'.
If the first letter of the encoded word isn't 'a', 'b', 'c', or 'd'
(for example 'mouse') this should be decoded to a space.
Write a function called decode which takes an encoded word as an argument,
and returns the correct decoded character.
Use your function to decode the following message:
'craft block argon meter bells brown croon droop'.
*/
//what is the input to the program
//craft
//what would be the output?
//f
/* //First try of the decode function
const decode = function(word){
switch(word[0]){
case 'a':
return word[1];
case 'b':
return word[2];
case 'c':
return word[3];
case 'd':
return word[4];
default:
return '';
}
};
*/
//Now that the function works, lets refactor it and make it better
//it should have the exact same output
const decode = function(word){
const charCode = word[0].charCodeAt();
//I want to decode a, b, c, d
//anything before or after should not matter
if(charCode < 97 || charCode > 100){
return ' ';
}
return word[charCode - 96];
};
//Input:craft block argon meter bells brown croon droop
//Output: forloop
/* //first cut at the decodeString function
const decodeString = function(str){
// extract words from string
const wordArray = str.split(' '); //[craft, block, argon...]
// send each word through the decode function to be decoded
const decodedArray = wordArray.map(word => decode(word)); //function(word){decode(word)}
//put each decoded letter together
const decodedString = decodedArray.join('');
//return the decoded string
return decodedString;
};
*/
//lets refactor it
const decodeString = function(str){
// extract words from string
// send each word through the decode function to be decoded
//put each decoded letter together
//return the decoded string
return str
.split(' ')
.map(word => decode(word))
.join('');
};
//console.log(decode('block')); //f
console.log(decodeString('craft block argon meter bells brown croon droop')); //f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment