Seriously, WTF? Why Javascript developer, even working for such a big company as Facebook, needs to know how to re-implement build-in language elements? Knowing everything about everything was bane of elementary education - we have all been trained (at least here, in Eastern Europe), that when we need to know something we shouldn't use 'outside' sources such as books then and Internet now. Why? Personally, I didn't know any developer who didn't sometimes read the documentation, especially if it takes less than 3s if you know what you are looking for.

In case that 'implementing sqrt()' task will ever occurs again, here are two of my JS implementations:) :

//in this way calculators implements square roots: var ownSqrt = function(number) { return Math.exp(Math.log(number)/2); }But if it is forbidden to use Javascript Math object constants at all, the best way is to use approximation like this:

var ownSqrt2 = function(number) { var x = number; while (Math.abs(x*x-number) > 0.001) x = (x*x+number)/(2*x); return x; }There are a lot of different algorithms on Wiki, and their implementations all over the Web.

This comment has been removed by the author.

ReplyDeleteBahaha. I like the first implementation, especially since it's just a mathematical obfuscation of Math.pow(x, .5) xD

ReplyDeleteOf course it is - programming is all about cheating, isn't it:)?

ReplyDeleteIt's a trick question. You would NEVER implement Math.sqrt() in javascript, since the existing Math methods are at a compiled level of javascript which is done at a speed that javascript could never match.

ReplyDeleteVery interesting article.. great examples..

ReplyDeleteJavaScript Training

JavaScript Training in Chennai

javascript tutorials

JavaScript Training in Chennai | Ecmascript 6 Training in Chennai | ES6 Training in Chennai | Angular 2 Training in Chennai | Yeoman Training | D3 Training | ReactJS Training | Gulp Training

ReplyDelete