Showing posts with label Lang. Show all posts
Showing posts with label Lang. Show all posts

Square root by Newton's method

This well known method to calculate square roots by successive approximations is one of the first examples that Martin Odersky uses in its Scala by example booklet freely available online. You'll find it in section 4 of chapter 4.

The idea of this method is that we guess what could be the result, and then iteratively improve our guess, until we reach a good enough approximation.

It doesn't matter much which is our initial guess, we could simply default it to one, more interesting is deciding when we should stop to iterate. In some way it should be dependent on the input value itself. Here we are going to consider ourself happy when the difference between our guess squared and the input, divided by the input itself is less than one thousandth:
def isGoodEnough(guess: Double, x: Double) = math.abs(guess * guess - x) / x < 0.001
So, we are going to accept 8.003 as approximation for the 64 square root, but we'll reject 8.004. To improve our guess we'll apply this algorithm:
def improve(guess: Double, x: Double) = (guess + x / guess ) / 2
Now we are ready to write the requested function:
def sqrtIter(guess: Double, x: Double): Double =
  if (isGoodEnough(guess, x)) guess
  else sqrtIter(improve(guess, x), x)
If the guess is good enough, we are done. Otherwise iterate again with an improved guess. Likely we don't want the user having the nuisance of providing an initial guess:
def sqrt(x: Double) = sqrtIter(1.0, x)
We can compare the result to call to the Scala library function:
println(sqrt(2) - math.sqrt(2))
println(sqrt(4) - math.sqrt(4))
println(sqrt(1e-6) - math.sqrt(1e-6))
println(sqrt(1e60) - math.sqrt(1e60))
We can, and usually want to, hide the implementation details, making them local to our function. A side effect is that we don't need anymore to pass around the x value, being that visible to all the local functions, too.
def sqrt(x: Double) = {
  def isGoodEnough(guess: Double) = math.abs(guess * guess - x) / x < 0.001
  def improve(guess: Double) = (guess + x / guess ) / 2
  def sqrtIter(guess: Double): Double =
    if (isGoodEnough(guess)) guess
    else sqrtIter(improve(guess))
  
  sqrtIter(1.0, x)
}

Go to the full post

AND and OR as functions

Let's create a couple of Scala functions that would provide an alternative implementation for the AND and OR logical operators. The point of this exercise is seeing how the well known if-else conditional expression works in Scala, and seeing again the difference between by-value and by-name parameter evaluation strategy.

We want to define two functions, and() and or(), behaving like && and ||. Remember that they are so called short-circuit operators. We don't need to check the && second operand when the first is false. Similarly the for ||, when the first operand is true.

Let's express our requirements with assertions:
assert(and(false, false) == (false && false))
assert(and(false, true) == (false && true))
assert(and(true, false) == (true && false))
assert(and(true, true) == (true && true))

assert(or(false, false) == (false || false))
assert(or(false, true) == (false || true))
assert(or(true, false) == (true || false))
assert(or(true, true) == (true || true))
Here is how I have implemented the two functions:
def and(a: Boolean, b: => Boolean) = if(a) b else false
def or(a: Boolean, b: => Boolean) = if(a) a else b
AND is implemented checking the first parameter. If it is true I need to check the second one, otherwise the resulting value is false. Dually for OR, if the first parameter is true, that is the result, otherwise it depends on the second one.

Notice that in both function I have specified that the second parameter is subject to a by-name evaluation. This follows from the short-circuit property of the logical expressions. We can see how this is useful when the second parameter is expensive to evaluate. Or even an infinite loop, as here below:
def silly() : Boolean = silly

assert(and(false, silly) == (false && silly))
assert(or(true, silly) == (true || silly))
The short-circuit logic is implemented also from my functions, so no need of evaluating silly().

Obviously, if I pass silly() as first parameter to either and() or or(), I enter in an infinite loop, and I should kill my Scala application.

Go to the full post

By-value vs. by-name

A pure functional programming language typically uses a by-need evaluation strategy for the arguments of function calls. Scala is a multi-paradigm programming language that also supports the imperative, in an object-oriented way, paradigm. This rules-out by-need, but would let think that the by-name approach would be followed. Still, reasons of efficiency pushed Martin Odersky to chose a by-value approach by default, and leaving the by-name as an alternative.

A trivial example should help clarify the difference about the two approaches.

Let's consider a useless function that gets as parameters a couple of integers and always returns zero.
def zero(a: Int, b: => Int) = 0
Notice that the first parameter is passed to the function by-value, while the second, as specified by the arrow "=>" notation, is passed by-name.

Function zero() looks pretty harmless. However, we could have big troubles if we use it in conjunction with something like this:
def silly() : Int = silly
Function silly() just resolves in an infinitive loop, that would let our program running forever without giving the user any satisfaction.

If I pass silly() to zero() as its second parameter, I'll have no problem at all:
println(zero(42, silly))
Being passed by-name, and not being actually used in zero(), silly() won't be evaluated.

On the contrary, you want to avoid this:
println(zero(silly, 42)) // !!!
Here silly() is passed by-value, this means that Scala tries to calculate its value to pass it to zero(), even if it has no use at all for it. And this would let the user waiting forever for its feedback.

Go to the full post

Three solutions to the loop problem

The lack of a block scope in JavaScript leads to what is often called The Infamous Loop Problem, where we try to use the (supposed) cycle variable in a for loop to set a callback function.

Conceptually, the solution is quite easy. The trouble is caused by the loop variable, that actually does not have a local scope, so we provide to it a local scope. In JavaScript we have only function scope, so a function would help us to find a way out.

The question is, which function? Whichever it is better for you in your context, I'd say. Let's see the three answers that I guess are more natural.

In the previous post I have written a buggy piece of code that was storing a few functions when looping on an array, an then, in another for loop, it called those functions. Now I modify it to let it work as I expected, following three different approaches.

Closure in loop

This is the most idiomatic solution using "pure" JavaScript. We wrap the code in the for loop around a closure, designed just to provide a local scope for the loop variable.
function doSomething(msg) {
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ];
var buffer = [];

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = (function(j) { // 1
        return function() { // 2
            doSomething(messages[j]);
        }
    })(i); // 3
}

// ...

for(var k = 0; k < buffer.length; ++k) {
    buffer[k]();
}
1. We put in buffer the function returned by a closure, here defined, that take as input a parameter, named j, that is assigned a value defined in (3).
2. The function returned by the closure is almost the same function we defined in the original code. The difference is that I don't use anymore the loop variable, but the closure parameter.
3. This is the core of the solution. I assigned to the closure parameter the loop variable, in this way the closure captures its current value, that now has a local scope, as required.

After a while, I guess this would look as the most natural approach, but if your JavaScript mileage is low, you could be find it a bit overwhelming. In this case, maybe you could be more at ease with the following variation.

Closure in the function

The idea is to move the closure from the for loop to the recipient function. I refactor the code above, rewriting the for loop and doSomething(), renamed doSomethingElse() for the sake of clarity.
function doSomethingElse(index) {
    return function() { // 1
        console.log(messages[index]);
    }
}

// ...

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = doSomethingElse(i); // 2
}

// ...
1. The closure has been moved here. Notice that this function does not run any code, but returns a function.
2. Just a simple assignment!

This code is so much readable, but I am losing the connection between the loop (2) and the reason why I need a closure in (1). Someone who reads just doSomethingElse() would probably wonder why it returns a closure instead of doing directly its job.

jQuery.each()

If we use the jQuery library, we can get the advantages of both the previous solutions using the each() method.

We use the original doSomething() function, and we don't need a closure in the for loop, jQuery.each() is a function, so it provides its own scope.
$.each(messages, function(index, value) { // 1
    buffer[index] = function() { // 2
        doSomething(value);
    }
});
1. For each element in the messages array, we call a function where the first parameter is the current index, and value the message element currently accessed.
2. There's no need of a closure, we simply assign to the buffer element a function that calls doSomething(). The capturing of local values is performed by jQuery.each().

Go to the full post

The JavaScript infamous loop problem

There is no block scope in JavaScript. Once you get used to this truth, the loop issue stops to be mystery, and you can say goodbye to a bunch of quirky behaviors in your code.

The for loop is a typical construct where many programmers get surprised by JavaScript. So I decided to write this post to make the issue as clear as I can. In the next post I present a few alternative solutions.

Simple loop through an array

Let's start looking at a plain for loop that won't give any trouble at all. I have an array of mixed objects, I want to call for each of them a function that does something not relevant here:
function doSomething(msg) { // 1
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ]; // 2

for(var i = 0; i < messages.length; ++i) { // 3
    doSomething(messages[i]); // 4
}
1. I don't care much of what this function actually does, logging the parameter is more than enough.
2. This is the array I want to loop through.
3. A local variable, i, is declared and used as temporary location for the current element in the array.
4. The function is called for each element in the array.

As I said, this way to walking through an array works fine. Still, we should be aware of the fact that the supposed loop variable is not actually limited to that scope, but it is available all over the function scope in which the for loop is placed.

This doesn't work

Let's think to something a bit more complicated. Say that I don't want to call immediately the other function, I want to create an array of function, so that I can call them later, after I do some other task.

I could (wrongly) think to refactor the previous piece of code in this way:
function doSomething(msg) {
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ];
var buffer = []; // 1

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = function() { // 2
        doSomething(messages[i]);
    }
}

// ...

for(var j = 0; j < buffer.length; ++j) {
    buffer[j](); // 3
}
1. Temporary place where storing the functions to be called in a second time.
2. For each element in the message array, I create an unnamed function that calls doSomething().
3. And after a while I call all the functions stored in the buffer.

At a first sight, it looks like we should have the same result of the first example. But here we get just a desolating list of "undefined".

What happened here? The problem is that the loop variable is not actually such. So, when in (3) we call doSomething() through the buffer, the index is the current value (actually, the length of the message array) and not its value when in (2) we assigned the function to the buffer.

What we need to do is to capture the current value of the loop variable in (2) so that would be used in (3). We can achieve this result in a couple of different ways, as we'll see soon.

Go to the full post

Selecting DOM elements

Selecting DOM elements of a given type in a document is a simple task, and we can easily do it using standard JavaScript functionality. Nevertheless, jQuery makes it even simpler.

Here is the code to get all the LI elements in the current document, both in plain JavaScript, and using jQuery:
var li = document.getElementsByTagName("li"); // 1
var $li = $("li"); // 2

console.log("li: ", li, li.length);
console.log("$li: ", $li, $li.length);
1. The getElementsByTagName() method returns a NodeList, a structure that is array-ish but does not derive from Array. It sports a property, length, that contains the number of element contained, and lets the user access each of them through the [] operator. An out of bound request is resolved to null.
2. A call to jQuery factory function returns a jQuery object that, for what we care here, is not different from a NodeList object, but it is enriched by extra-information and functionality, that could be useful in more a demanding context.

Go to the full post

When this does not work, use that

There is an issue in "this", the JavaScript keyword identifying the current object.
It works fine in an object member functions (AKA methods) but not in their inner functions. An easy way to bypass the problem requires us to create a member variable, that is often called "that" (or "self", but it is usually considered a weaker option).

Does it remember you an Abbott & Costello skit, "who's on first?", or it is just me? Anyway, an example should help clarifying the matter.

Say that we want to have an object, named calculator, keeping an internal status and providing a couple of methods, opA() and opB(), to perform some obscure calculations. The first operation is not too complicated, but opB() requires some messy stuff to be done, and we think that it would be a good idea to organize it defining an inner function that, among the other things, calls a free function.

It should be all not too complex to do, still we have to deal with the above mentioned issue.
var elaborate = (function(x) { // 1
    var cache = 0;

    return function(x) {
        cache += x;
        return cache;
    }
}());

var calculator = {
    status: 0,
    opA: function(x) { // 2
        this.status += x;
    },
    opB: function() { // 3
        var that = this; // 4
        var somethingComplicated = function() {
//            this.status += elaborate(this.status); // 5
            that.status += elaborate(that.status); // 6
        };
        
        somethingComplicated(); // 7
    }

    calculator.opA(3);
    calculator.opA(4);
    calculator.opB();
    console.log(calculator.status);
};
1. I defined elaborate() as a closure, so that it could keep its own status. See details in a previous post, static variable by closure.
2. This first method is trivial. It gets a parameter in input (assumed to be a numeric value), and adds it to the object property (status). To access the object property the keyword "this" is used. Not an issue here, for the object methods, the bind between "this" and the object itself is correctly done by JavaScript.
3. More complications here. In opB() we define a function, somethingComplicated(), that calls elaborate(), the closure defined in (1). The issue is that we can't use "this" in the body of somethingComplicated(), because "this", at that point, refers to the global scope or is undefined (if we "use strict" JavaScript, as we should).
4. "this" don't work as we would like in inner functions, but we can patch this behavior defining a local variable in the function, often called "that", that stores the value of "this" so to do as a bridge to the inner function.
5. As said above, this line doesn't work. "this" is undefined ("use strict") or points to the global scope. Hardly what you usually need.
6. This line saves the day. We use "that" to get access of the unavailable "this".
7. So we can happily call our somethingComplicated() inner method.

Go to the full post

Strictly or loosely false

Being Javascript a loosely typed language, comparing a value for its truthiness could lead to an unexpected behavior if you, well, do not expect it.

To perform a strict checking, you should use the strict comparison operator "triple equals", and you should be aware that by default the loose "double equals" operator is used.

There is a bunch of values that are loosely evaluate as false (friendly known as "falsy"):
var myUndef, // undefined
    myNull = null,
    myFalse = false,
    myEmpty = '', // empty string
    myZero = 0, // numeric zero
    myNan = parseInt('not a number'); // parsing a non numeric string returns NaN
    
if(myUndef || myNull || myFalse || myEmpty || myZero || myNan) // 1
    console.log('Unexpected');

try {
    if(myNotExisting) // 2
        console.log('Unexpected');
}
catch(e) {
    console.log(e);
}

if('false') { // 3
    console.log('Misleading');
}
1. All these values (undefined, false, empty string, zero, NaN) are loosely equals to the boolean false value, so the next line is not executed.
2. This variable was even not declared, checking it results in an exception of type ReferenceError.
3. The string 'false' is not converted to the boolean false value, and it is evaluated to true.

Go to the full post

String and regular expressions

The JavaScript String class has a few methods that could be used with RegExp. Here is a breaf introduction to them: split(), search(), match(), and replace().

split

Regular expressions make String.split() more flexible:
"1, 2, 3".split(", "); // 1
"1 ,  2 ,3".split(/\s*,\s*/); // 2
1. This is how is commonly called split(). If we are sure on how the separator is, it works fine, and returns an array of three elements containg just the numbers. But what if we have no control on the blanks? And we could have no blanks, or many of them, around a comma? You usually won't be happy with the result.
2. This is the solution. A comma is the real separator, and any blank around it is eaten out.

search()

Passing a RegExp to search() on a specified string, we get back an integer representing the index of the first match, or minus one if there is no match:
"JavaScript".search(/script/); // 1
"JavaScript".search(/Script/); // 2
"JavaScript".search(/script/i); // 3
"Here is 1 for you, 3 for me, 42 for the others.".search(/\d+/g); // 4
1. The search is by default case sensitive, so the pattern here is not found, and the function call returns -1.
2. The match is found starting on 4.
3. We can override the default, saying that we want to perform a case-insensitive search, specifying the "i" flag after the pattern. This function call returns 4.
4. The global option makes no sense in this context, and it is silently ignored. The returned value is the position of the first match, 8.

match()

The match() behavior is quite articulate. Its output should be interpreted differently accordingly to the provided input. Seeing it in action should clarify what I mean:
var s = "Here is 1 for you, 3 for me, 42 for the others.";
s.match(/\d+/); // 1
s.match(/\d+/g); // 2
"My email address is someone@not.existing.zzz".match(/(\S*)@(\S*)/);
1. We ask to match() to return just the first subsequence matching the specified pattern, in this case a string of one or more digits. It returns a vector containing one element, "1".
2. Global matching, a vector is returned containing all the matching elements, in this case three strings, "1", "3", and "42".
3. The RegExp represents an email address, first part is the sequence of not-blank characters before the "at" symbol; second part is what is after it, till we get a blank. Notice that we asked match() to capture $1 and $2 as left and right side of the "at". In this case match() returns an array containing in first position the full matching element, and in the next positions $1, $2, ...

replace()

This function returns a copy of the original string where, if the RegExp is found, it is replaced by the second parameter passed:
"... javaScript ... javascript ... Javascript ...".replace(/javascript/gi, "JavaScript"); // 1
"I want to have 'doublequotes' in this string!".replace(/'([^']*)'/g, '"$1"'); // 2
1. Notice the two flags associated to the RegExp, specifying that we are preforming a global and case insensitive search. All the three JavaScript variation in the string are found and replaced by the string passed as second argument to the function.
2. What we are saying here is: search for each {g option} sequence starting with a single quote {'}, followed by any number {*} of any character but a single quote {[^']} and a single quote, and call $1 the subexpression in the round parenthesis. Then replace what you have found with a double quote, the $1 subexpression, and another double quote.

Go to the full post

Factory pattern for a more robust constructor

A JavaScript constructor is just a simple function. It should be called through the "new" operator so that it would provide its added value of setting "this" to refer to the newly created object, inheriting from the function prototype, and returning a reference to "this" object. But what if a client programmer mistakes the sense of our construct, and calls it as a simple function?

Let's think what happens when the constructor I defined in the previous post is called directly:
function Rectangle(a, b) {
    this.a = a;
    this.b = b;
}

// ...

var rx = Rectangle(6, 7); // !! bad mistake !!
So, I forgot to use "new", and Rectangle is treated by JavaScript as a normal function call. What happens is barely that, in the global scope, two properties named a and b are created (if not already there) and set to 6 and 7. Then "undefined" is returned and assigned to the variable rx.

Is this what I really wanted to happen? Hardly so. And even in that case, I should have used a different function to make clear that it was intentional, and not a silly mistake.

I can think to a couple of ways to improve my code: signaling the user programmer that he is doing something unexpected, or silently transform his mistake in the right thing. In the first case I would typically throw an exception, in the second one I would use the factory pattern.

Throwing an exception

This is the most clean but unforgiving solution. To implement it, we check "this" in our constructor function. If it is not associated to the instance of the function, it means that the user didn't call it properly. So we raise an exception, and the let the user programmer the burden to deal with it.
function Rectangle(a, b) {
    if(!(this instanceof Rectangle))
        throw 'Remember to use "new" to call a constructor!';
    
    this.a = a;
    this.b = b;
}

// ...

try {
    var rx = Rectangle(3, 4);
}
catch(e) {
    console.log(e);
}
As I said, this is clean code, and if you have a background in languages supporting static type, you should appreciate the predictability of what it is going on here. The caller does something wrong, he gets a rigorous "no, no" back.

Still, it doesn't looks right to me, when compared to the normal JavaScript behavior.

Factory pattern

Less clean, more forgiving. If someone calls a constructor as a simple function, we patch his code on the fly, converting it to a proper constructor call. The user programmer could now create a new Rectangle calling the constructor as was originally expected, or as a normal function:
function Rectangle(a, b) {
    if(!(this instanceof Rectangle))
        return new Rectangle();

    this.a = a;
    this.b = b;
}

// ...

var rf = Rectangle(12, 2);
// ...
Your choice

I feel that using the factory pattern is more in the JavaScript way of writing code, but I guess this is a matter of which kind of application you are developing, team programming conventions, and the such.

In any case, I would suggest you to choose one of the two approaches (or three, if you think that, after all, not checking is a viable option), and keep it in all your project.

Go to the full post

JavaScript constructor

If you have a background in strong-typed programming languages (as I have, incidentally), the JavaScript concept of class could look fuzzier than expected.

Here I show a standard way of defining a class, with a variation.

You are need in your code a lot of rectangles. In C++, Java(, etc), you would define a class Rectangle, and put in it all the relevant data and method. The JavaScript approach is different: you define a function where you create its associated data properties, using the parameter passed by the user, and let the function inherit from its prototype all the other properties you need.

This function smells like a constructor, acts like it, so it is actually called constructor, and typically given a name starting with an uppercase letter to visually show that here there is something special. But remember that, from the JavaScript point of view, it is just a plain function. The magic is done when we call it through the "new" operator. It is its job to perform the association between the constructor and its prototype, and make the constructor return by default its "this" pointer.

Here is an example where I define, instantiate, and use a Rectangle:
function Rectangle(a, b) {
    this.a = a;
    this.b = b;
}

Rectangle.prototype = {
    constructor: Rectangle, // 1
    toString: function() { return "a = " + this.a + ", b = " + this.b; }, // 2
    area: function() { return this.a * this.b; },
    perimeter: function() { return 2 * (this.a + this.b); }
}
    
var r = new Rectangle(4, 10); // 3
console.log("rectangle: ", r.toString()); // 4
console.log("area: ", r.area());
console.log("perimeter: ", r.perimeter());
console.log("Is r a rectangle? ", r instanceof Rectangle); // 5
console.log("Rectangle constructor: ", Rectangle.prototype.constructor); // 6
1. Backlink from the Rectangle prototype and its constructor.
2. All the JavaScript objects have a toString() method, here we redefine it to give some useful information to this specific type.
3. This is the core of the story: we call Rectangle through the "new" operator. If we forget to do it, we do not create a new object, we simply call a function that creates a couple of properties in the global scope and returns an undefined value.
4. Now we can use r as a Rectangle object.
5. Notice that the instanceof operator performs a check of the object against a constructor. Actually it won't check if the object has been built through that constructor, but if it inherits from the constructor's prototype.
6. If you comment out the line (1), you'll see here why we need it. Defining a function prototype as showed, leads to overwriting the default constructor property, breaking the backlink to that function. So we have to reset it.

To avoid the nuisance of (6) we could create just the properties we really need, and not redefine the complete prototype:
Rectangle.prototype.area = function() { return this.a * this.b; };
Rectangle.prototype.perimeter = function() { return 2 * (this.a + this.b); };
Rectangle.prototype.toString = function() { return "a = " + this.a + ", b = " + this.b; };
Choose whichever approach you think is more suitable to you.

The weakest point in this design is in (3). Rectangle is just a function, calling it directly is not an error, from the JavaScript perspective, even if it almost ever it doesn't make much sense and leads to a disaster.

Using the factory pattern our code would be stronger, as I am going to show in the next post.

Go to the full post

Currying and binding

If you wonder where the term currying is coming form, the answer is in the Haskell Brooks Curry logician name, and it refers to the partial application of parameters to a function. In JavaScript this is done by the bind() method, defined in ECMAScript 5.

And if you wonder what is all this fuss about binding and currying, you probably don't have a background in functional programming or, as it is my case, in C++. But don't worry, it is easy to catch up, and I reckon you are going to fall in love with them too.

Say that you have written a complicated function, you spent a lot of time to develop, test, and maintain it. You are very happy with it, and your users too. Let's simulate it with something a bit simpler:
function sum(x, y) {
    return x + y;
}
Then you find out that your cool function is often used passing always only a "real" parameter, being the other just a constant. In my example, the story would be that I wrote a sum() function, but I find out that the users often need just an increase(). Duplicating the code looks a poor solution, it would be better to create an adapter that provides just a more natural interface to the user, but keep almost all the coding effort in the original function.

Here I define next(), as a synonym of sum() that always uses 1 as a first parameter, and lets the user specify the other one:
var next = sum.bind(null, 1);

console.log("original interface", sum(42, 1));
console.log("more natural solution", next(42));
Good. But what is the null I passed to bind() as first parameter?

The fact is that JavaScript() bind() is not only about currying but, as its name suggests, it also performs an optional binding of the function to a specified object. In the previous case we didn't have any object interested in this feature, so I just passed a null instead.

To see bind() in full action, let's change a bit the startup condition. We already have an increasing function, but now it is a method, bound to an object:
var calculator = {
    step: 1,
    increase: function(x) {
        return this.step + x;
    }
};
console.log(calculator.increase(42));
calculator.step = 2; // 1
console.log("Double step: ", calculator.increase(42));
As we see in (1) it is pretty simple to change the increasing step in my calculator, but the user it is not completely happy with this solution. He didn't care of such a flexible solution, what he needs is just a function that returns its passed parameter increased by 2.

Luckily, we know that using bind() we can associate a function to different object, like this:
var step2 = calculator.increase.bind({step: 2}); 
console.log(step2(42));
We call bind() on the calculator.increase() method, and we pass to it as first (and only) parameter its new "this". In this case we don't want the step to be modifiable by the user, so we pass the object anonymously, making its reference lost to the outside world.

Go to the full post

One scope, more closures

JavaScript uses closure as an elegant way to hide a function internal status the rest of the world. It is simple to extend the concept and let more closures share the same variables.

My original sequence generator had its status defined as a property, and as such visible by everybody who had access to the function itself. I decided that was bad, and I refactored it as a closure. Cool, but the client programmer needs to modify the sequence internal status, to be able to skip ahead of a few numbers when needed.

To achieve this result, we need to do a substantial change to our code:
var sequence = (function() {
    var current = 0;
    return { // 1
        get: function() { // 2
            return current++;
        },
        skip: function(delta) { // 3
            if(delta > 0) // 4
                current += delta;
        }
    }
}());
1. The external anonymous function does not return anymore a single function, but an object containing a couple of properties, that happens to be functions.
2. The first property is named get, and it actually is our old sequence generator.
3. Here is the required improvement, a function named skip that changes the sequence generator internal status.
4. I didn't provide much error handling to the code, but I couldn't help to put at least this line, meant to avoid the user to move the sequence back and forth.

A use test for the new sequence:
for(var i = 0; i < 3; ++i)
    console.log(sequence.get()); // 1
sequence.skip(3); // 2
for(var i = 0; i < 3; ++i)
    console.log(sequence.get());
1. Get each time a new sequence number, starting from zero.
2. Skip three numbers in the sequence, before getting more numbers.

Go to the full post

Closure for static variable

Function static variable in JavaScript are easily emulated by function property. But if we want to make it private to the function, we'd better use a closure.

The first times you see a JavaScript closure at work, you could get lost in the code, but being it such a common paradigm, you are going to get used to it in almost no time:
var sequence = (function() { // 1
    var current = 0; // 2
    return function() { // 3
        return current++;
    }
}()); // 4

for(var i = 0; i < 3; ++i)
    console.log(sequence());
1. We define as a variable as ... what? There's an anonymous function definition starting here, and if we jump to (4) we see that the function is invoked just after being defined.
2. In the function body we see a local variable definition, that results being private to the function. No way anyone outside could see or modify it.
3. And here we see what our anonymous function returns: another function! This internal function does the dirty job of post-incrementing the current sequence number and returning it.
4. This means that JavaScript has to invoke the anonymous function, that returns the internal function, that returns - when called - the sequence number.

A bit contrived, isn't it? But the good news is that now we can simply call our "sequence" variable to increase and get the sequence number, exactly in the same way we called the original sequence generator. And, as required, its internal status is not visible anymore from outside.

Go to the full post

Static variable emulation

Keeping in mind that JavaScript considers functions just like specialized objects, it is easy to define something that acts like a C static variable.

As an example, let's see how we can implement and use a sequence generator:
sequence.value = 0; // 1
function sequence() {
    return sequence.value++; // 2
}

for(var i = 0; i < 3; ++i)
    console.log(sequence()); // 3
1. Define a property named value in the sequence function, initialized to zero. In this way we don't pollute the namespace in which the function is defined with a name that is used just by the function.
2. The current value is returned and then incremented.
3. Calling our function we get a new increased value each time.

This could be good enough in many case, but the fact that the internal status of the sequence function is visible and modifiable from anyone that sees the function itself could be sometimes worrisome.

A better solution, as we'll see soon, is to refactor our sequence function to become a closure.

Go to the full post

The Math object

The JavaScript developer has access to a bunch of commonplace mathematical constants and functions through the Math object. As official reference you should check the ECMA-262 5.1 standard, even if I should confess that I find more readable the Mozilla Developer page.

To calculate a circumference, it is nice to have a PI constant available:
var radius = 1;
var circ = 2 * Math.PI * radius;
console.log("Circumference is ", circ);
The resulting value should be something around 6.283185307179586.

We can convert a number to integer by approximation using round(), or we can use ceil() and floor(), to flatten the result to the left or to the right.
Let's see what happen applying these functions to the natural logarithm of 10:
var value = Math.LN10;
console.log(Math.floor(value), " <= ", value, " <= ", Math.ceil(value));
console.log("Rounding", value, " -> ", Math.round(value));
The max() and min() functions accept in input any (reasonable) number of parameters, and its returned value is the bigger or smaller one in the lot.
var values = [ -42, 5, Math.E ];
console.log(Math.max(values[0], values[1], values[2]));
console.log(Math.min(values[0], values[1], values[2]));
Min is -42, max is 5.

There are also the usual functions to calculate exponential values, Math.exp(), logarithm,

Math.log(), power, Math.pow(), a short cut for square roots, sqrt(), and the common trigonometric functions.

Playing around with JavaScript numerical functions, you can end up getting Infinity, -Infinity, and NaN.
console.log("Divide by zero:", 3 / 0); // Infinity
console.log("Divide by zero:", -3 / 0);  // -Infinity
console.log("Not a number:", 0 / 0);
console.log("Not a number:", Math.sqrt(-2)); // Nan

Go to the full post

Primitive or wrapper object?

JavaScript is a very forgiven language, we can often be very vague when considering the type of a variable. Usually we can think of primitive instances almost as if they were wrapper objects. Still there is a subtle difference, and we'd better be aware of it.

See this variable definition:
var rawStr = "test"; // 1
var objStr = new String("test"); // 2
1. A primitive string is defined.
2. A wrapper object String is defined.

The two variables could be usually considered as identical, still they are not strictly the same:
if(rawStr == objStr) // 1
    console.log("rawStr is a " + typeof(rawStr) + ", objStr is a " + typeof(objStr));
if(rawStr !== objStr) // 2
    console.log("strictly speaking, a string is not equal to an object String");
1. A raw string and a wrapper String containing the same sequence of characters are loosely seen as equal, but the typeof() operator shows that they actually have a different type (string and object).
2. If we strictly compare them, we see that they are actually different.

Same behavior applies to numbers and booleans:
var rawNum = 42;
var objNum = new Number(42);
if(rawNum == objNum)
    console.log("rawNum is a " + typeof(rawNum) + ", objNum is a " + typeof(objNum));
if(rawNum !== objNum)
    console.log("strictly speaking, a number is not equal to an object Number");

Go to the full post

Hello JavaScript, and null vs. undefined

The cool thing about JavaScript, is that you don't need almost anything to start working with it. If you reading this on a modern browser, you should have already all at hand. Maybe, if you are on Firefox, you would prefer to do download a plugin (and I'm thinking to Firebug) to have some debugging fire power. And that's it. You are ready to write your first JavaScript application.

My Hello World JavaScript application amazingly does some little more than greeting the user. It also shows what is the difference among null and undefined in this language.

If you have any reason not to use the console object, that lets you to write log without pestering the browser with a popup, you could fallback to the old, and annoying, alert() function.

Here is the HTML that I have written:
<html>
<head>
    <title>Hello JavaScript</title>
    <script type="text/javascript"></script>  <!-- script language specification -->
</head>
<body>
    <script>
        var a; // 1
        var b = null; // 2
        
        if(a == b) // 3
            console.log("undefined is loosely equal to null");
        if(a === b) // 4
            ;
        else
            console.log("undefined is strictly not equal to null");        
        
        document.write("Hello World!"); // 5
    </script>
</body>
</html>
If you are new to JavaScript there are a few interesting things to notice.

In the head section I specified the scripting language I am about to use. JavaScript is understood by a large share of browsers, and often it is assumed by default. But it is always a good idea to document that we are actually using it. Here I am writing HTML code, so the associated comment on the right is a HTML comment (less than, exclamation mark, minus minus ... minus minus, greater than).

In the body I specify a script section and in it I do a few things. Notice that here I am actually writing JavaScript code, so I follow its conventions. Among the other things, we can see that comments are in Java style, a double slash till the end of the line. I could have used also the C/C++ old-style comments (slash, star .... star, slash).
1. A variable is declared but not defined.
2. Another variable is declared, but here it is also defined, even if the associated value is just a null.
3. Undefined is similar to null, and the standard comparison operator is sort of fooled to see them as equals, so the next line is actually executed. We can see the output in the Console tab of Firebug.
4. But undefined is not the same of null, and the strict comparison operator is smart enough to detect the difference, so the next (empty) block is not executed, but we jump directly to the "else" block, and we write that log to the console.
5. In any case we politely say hello to the user.

Go to the full post

Map subsetting by keySet().toArray()

I recently faced a non-standard request, for which I implemented a solution that doesn't make me completely happy. But I have not much time to ponder of it, and it works. I write it down here, so that maybe someone (or myself in the future) could show me a better alternative.

Developing for Java 6, using just the core functionality. It is given a map of Strings and whatever, and an index of one of its elements, we want to reduce the original map to a subset such as: (1) the resulting map would contain 10 elements maximum, (2) the element given by index would be the first, (3) the traversing map order is preserved.

We don't know the actual type of the map object in input, we know only that it implements the Map interface, meaning that we can't use the handy SortedMap.subMap() method.

My first idea was iterating on the map associated entry set, removing all the items before the index, then executing a dummy loop for ten times, before removing the tail elements (if any). It works, but the central dummy loop is quite boring.

So I opted for going through the keySet map, converting it to an array, so that I could randomly access any element in it:
String[] keys = (String[])myMap.keySet().toArray(new String[myMap.size()]); // 1
for(int i = 0; i < first; ++i) // 2
    myMap.remove(keys[i]);

for(int i = first + max; i < keys.length; ++i) // 3
    myMap.remove(keys[i]);
1. This line is painful. Given a myMap object (it instantiates a class that implements the Map interface, as described above), we call on it keySet(), that returns a set, on it we call the toArray() method, that converts it to an array. I have already written something on the toArray() involuted syntax, using this overload we can specify the actual type of the returned array. 2. Assuming first is an int variable, representing the index of the elements we are interesting it, defined before this code snippet. Here we are removing the leading elements. 3. The max variable stores the maximum number of elements we want to have in the resized map. The effect is removing all the trailing elements.

Go to the full post

Copying a multidimensional array

The handy Arrays.copyOf() function helps us to perform elegantly an array copy, when cloning is not a viable option.

The nuisance is that it is limited to monodimensional array. What if we have to copy a two (or more) dimensional array? We can still use Array.copyOf() for the actual data copy, but we have integrate it with some "by hand" coding, to allocate memory for n-1 dimensions.

I guess that showing a twelve-dimensional example would be funnier, but let see instead a mere, an more common, bidimensional array copy.
int[][] source = {
   {1,2,3,4},
   {3,4,5,6},
   {5,6,7,8},
};

int[][] destination = new int[source.length][]; // 1
for(int i = 0; i < destination.length; ++i)
   destination[i] = Arrays.copyOf(source[i], source[i].length); // 2
1. A Java bidimensional array is nothing more than an array of arrays. What we are doing here is the first step in the copy, allocating enough memory in destination to store the arrays that are going to be created in the subsequent for loop. 2. Last step, create a copy of each one-dimensional array and store it in the just allocated room in destination.

Go to the full post