My first attempted Kata on Codewars

In the Autumn of 2015 towards the end of October, I’d finally got into Codewars -Yay!  So it was time to start on doing a kata challenge.  I didn’t know where to start, so I thought I’d start with one that would be challenging but as it was my first not too challenging.   After a short while I came across a problem which was simply to implement the following code.

[2,5,1,3].max() // returns 5

[1,2,3,8,4,9,7,42,99].max() // returns 99

[2,‘5’,1,3].max() // returns 5

[2,5,1,‘ab’].max() // returns NaN

I thought this is straight forward and went away and wrote the following, this is exactly as I wrote it warts and all

Array.prototype.max = function (max1) {

                    return Math.max.apply(Math, this);

};

var max1 = [2,5,1,3].max();

Array.prototype.max = function (max2) {

                     return Math.max.apply(Math, this);

};

var max2 = [1,2,3,8,4,9,7,42,99].max();

Array.prototype.max = function (max3) {

                     return Math.max.apply(Math, this);

};

var max3 = [2,‘5’,1,3].max();

//Array.prototype.max = function() {

//var maxItem = +this.sort()[this.length-1];

//return Number.isFinite(maxItem) ? maxItem : NaN;

//};

Array.prototype.max = function (max4) {

                      return Math.max.apply(Math, this);

};

var max4 = [2,5,1,‘ab’].max();

I built it, it passed the tests and I submitted – success and a huge smile on my face.

Then I saw what others had done and I realised while my code works, its only half the battle.  Can you do it better, I know that we are all under pressure but we should be asking can I improve on this. Whilst I did it in multiple lines and passed different parameters into the same code 4 times. To achieve the same result, have a look at this:

Array.prototype.max = function() {

                   return Math.max(…this);

}

Simple, elegant and clever plus it is about 10% of the code I wrote.  Whilst I was pleased to get the points, I still have much to learn, as they say its the journey that counts

Leave a Reply

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