Katas revisted

I’m going to take a short break from ‘this‘ and go back to the katas I have done on code wars, not every single one, currently at the time of writing there are 115 done.  What I will be doing is revisiting some of the earliest katas I did and write down the way I did them then take a look at the solutions much better than mine.

 

Before I got onto codewars I was faced with two challenges both times the code was given and needed to be tinkered by me for it to run correctly.  The first was the following

function multiply(a, b){
a * b
}

When I first saw this I hit the semi-colon key and submitted.  I was too excited to notice that what I was actually being asked was that the majority of functions stop executing when they reach the return statement.  So the answer I gave:

function multiply(a, b){
return a * b;
}

I thought OK that is short and to the point then I looked at the solutions others gave and boy I was stunned.  There were avenues I had not even thought about.  My favourite was

function multiply(a, b){

    if (!a || !b || typeof(a) != “number” || typeof(b) != “number”) {

         return 0;

}

    return a * b;

}

This solution, although having more code accounts for the possibility that the parameters a and b may not be numbers as expected, and if they are not the function returns 0.  Then the parameters are numbers and the code I came up with is present.

The very next codewars challenge was to tidy up the following so it would execute.

function Person(name){
this.name = name;
}

Person.prototype.greet = function(otherName){
return “Hi ” + otherName + “, my name is ” + name;
}

This was simply about the addition of a ‘this’ keyword.  Which I did here.

function Person(name){
this.name = name;
}

Person.prototype.greet = function(otherName){
return “Hi ” + otherName + “, my name is ” + this.name;
}

This time I actually did hit the best practise solution the was one which although clever was not that elegant.

function Person() {

return {

greet: function() {

return “Hi Kate, my name is “ +

[“Joe”, “Jane”][Math.floor(Math.random() * 2)];

}};

}

Back to my solution the code without my tinkering the name is referencing the global variable, however it does not exist, and NOT the Person.name property. so by adding the this.name the code now points to the actual Person como comprar viagra en espa.name property.  The greet function is another property of the Person object.  So When we invoke this.name within the lexical scope of greet, we’re referencing back to the parent object, i.e. Person, which allows us to access its other properties as well. In this case, name.

This allowed me to get into codewars and on with my journey

Leave a Reply

Your email address will not be published. Required fields are marked *