Monday, 28 December 2015

Kata Day 33: 80's Kids #7: She's a Small Wonder


Problem Description: Vicky is quite the small wonder. Most people don't even realize she's not a real girl, but a robot living amongst us. Sure, if you stick around her home for a while you might see her creator open up her back and make a few tweaks and even see her recharge in the closet instead of sleeping in a bed.

In this kata, we're going to help Vicky keep track of the words she's learning.

Write a function, learnWord(word) which is a method of the Robot object. The function should report back whether the word is now stored, or if she already knew the word.

Example:

var vicky = new Robot();
vicky.learnWord('hello') -> 'Thank you for teaching me hello'
vicky.learnWord('abc') -> 'Thank you for teaching me abc'
vicky.learnWord('hello') -> 'I already know the word hello'
vicky.learnWord('wow!') -> 'I do not understand the input'

Case shouldn't matter. Only alpha characters are valid. There's also a little trick here. Enjoy!

Level:6kyu

Link to Kata: 80's Kids #7: She's a Small Wonder

Our aim in this Kata was to give a word to Vicky the robot and she will check if its a valid word or not. Then if she doesn't recognize this word from her memory then she will store the word for future use in her memory and thank you for helping her learn that word otherwise if she already knows the word then she will tell you that she already knows the given word.

I initialized an array in Robot function as this.arr so that its value can be used down the line in the object of Robot class. In learnWord function I initialized a variable res in which I will store vicky's response. Vicky has some responses from which we know that she already knows those words so I initialized those words in an array knowledge. 

I split the input word using the space delimiter and then check that the length of this array is equal to 1 and the word is not empty. If the above two conditions are satisfied then I change the given word to lower case in order to avoid case conflict. Using regex I check if the given word contains only alphabets and no numbers or special characters. If the above condition is true then the index of given word is checked in the this.ans array and knowledge array and if the index in both the cases is -1 then I push the given word to this.ans array and put vicky's response as thank you and return the res.

If the above condition is not satisfied and the word is already present in this.arr or knowledge then I put vicky's response as "I already know this word" and output the response. In all the other cases vicky's response would be that the given word is invalid.

Here is a link to the code: Kata Day 33

Please mention your suggestions or your doubts in the comment below.

Happy coding. :)

No comments:

Post a Comment