What is wrong with the following code:
Coffeescript:
sqrt = (n) ->
small = 0.01
lo = 0
hi = (n+1)/2
while hi > lo
mid = (lo+hi)/2
diff = Math.pow(mid, 2) - n
sign = (diff > 0) ? 1 : 0
if Math.abs(diff) < small
return mid
else
switch sign
when 1
hi = mid
when 0
lo = mid
console.log (sqrt 33)
Javascript:
// Generated by CoffeeScript 1.3.3
(function() {
var sqrt;
sqrt = function(n) {
var diff, hi, lo, mid, sign, small, _ref;
small = 0.01;
lo = 0;
hi = (n + 1) / 2;
debugger;
while (hi > lo) {
mid = (lo + hi) / 2;
diff = Math.pow(mid, 2) - n;
sign = (_ref = diff > 0) != null ? _ref : {
1: 0
};
if (Math.abs(diff) < small) {
return mid;
} else {
switch (sign) {
case 1:
hi = mid;
break;
case 0:
lo = mid;
}
}
}
};
console.log(sqrt(33));
}).call(this);
Another thing is when you are in the infinite loop or recursive calls, you cannot even open the console. The browser just freezes. This is so annoying. Anyone can shed light on this too?
This part:
Should be:
The
?is reserved for the existential operator.See also: documentation