[JavaScript Quiz #15] All possible compositions of a number

Today’s JavaScript quiz is about finding all the possible compositions of a number. For example if we have a number 4, we would like to find all the possible compositions that sums up to 4 as follows.

1111
112
121
13
211
22
31
4

.
.
.
.
.
.
.
.
.
.
.
.
.
In order to develop this utility, it is important to understand its nature. For a number n, it has the following possible compositions:
n (for a composition length of 1)
1 n-1 (for a composition length of 2)
1 1 n-2 (for a composition of length 3)

1 1 1 … 1 (for a composition of length n)

This can be handled using recursive function as follows.

function compositions(n, temp, output) {
    var i, newTemp;
    
    if (n == 0) {
        output.push(temp);
    } else {
        for (i = 1; i <= n; ++i) {
            newTemp = temp + i;
            
            compositions(n - i, newTemp, output);
        }
    }
}

As shown, the base is if n is equal to 0 then we add the temp string (which is initialized to "") to the output list, else we subtract i from n and adds i to the temp string. The following function getAllCompositions calls compositions with the initial values.

function getAllCompositions(n) {
    var out = [];
    
    compositions(n, "", out);
    
    return out;
}

Finally, we can test getAllCompositions as follows.

// Test ...
var num = 4;
var out = getAllCompositions(num), i;

console.log("Compositions number for (" + num + ") = " + out.length);
for (i = 0; i < out.length; ++i) {
	console.log(out[i]);
}

The output will be:

Compositions number for (4) = 8
    
1111 
112 
121  
13 
211  
22  
31  
4

If you have a better solution, feel free to put in the comments below. The current solution complexity is n!.

JavaScript Quiz #13

Assume that we have the following short JavaScript code:

<script>
    var result = 3..valueOf() + (1, 2, 4);
    alert(result);
</script>

Will this code succeed or fail? and if it succeeds, what is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The final result is 7. Let’s understand why we will have this result. Let’s divide the expression in two parts. In the first part, we have:

3..valueOf()

This expression will work fine because in JavaScript, it is valid to trail decimal points in float numbers, so for example 3 can be represented as 3 or 3.0 or 3. (without having to mention the extra 0 after the decimal dot).
So the expression can be read simply as (3.).valueOf() which will return 3.

The second part is straightforward:

(1, 2, 4)

In order to know the result of this expression, we have to know how expressions work with the comma operator, if we have an expression that contains many comma operators then this expression will be evaluated to the last mentioned value. This means that
(1, 2, 4) will be evaluated to 4.

Adding the first part result to the second part result will result in: 3 + 4 = 7.

JavaScript Quiz #12

Assume that we have the following short JavaScript code:

<script>
    var number = 50;
    var obj = {
        number: 60,
        getNum: function () {
	    var number = 70;
	    return this.number;
	}
    }; 

    alert(obj.getNum());
    alert(obj.getNum.call());
    alert(obj.getNum.call({number:20}));
</script> 

Will this code succeed or fail? and if it succeeds, what is the output of the alerts?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The alerts will output 60, 50 and 20. Let’s understand why we will have these results.

The sequence of operations:
1. In obj.getNum(), this.number will return number in obj scope which is 60.
2. In obj.getNum.call(), this.number will return number in global scope because Function.prototype.call‘s first parameter is not
specified which mean that the scope will be the global scope. So the result will be 50.
3. In obj.getNum.call({number:20}), this.number will return number in the object scope specified in the first parameter
of Function.prototype.call method which is {number: 20}. So the result will be 20.

More information about Function.prototype.call() can be found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

JavaScript Quiz #11

Assume that we have the following short JavaScript code:

<script>
    var x = !!"Hello" + (!"world", !!"from here!!");
    
    alert(x);
</script> 

Will this code succeed or fail? and if it succeeds, what is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The alert will output 2. Let’s understand why we will have this result.

The following sequence of operations occurs:
1. !!"Hello" ==> This operand will be evaluated to !false which will be finally true.
2. (!"world", !!"from here!!") ==> The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. which means that !!"from here!!" will be returned and will be evaluated to true.
3. As none of the operands is of String type, the + operands will be converted to number which means true + true will be evaluated to 1 + 1 which will equal finally 2.

JavaScript Quiz #9

Assume that we have the following short JavaScript code which runs on a browser that is ECMA 5 compatible:

<script>
    var x = [1, 2, 3, 4].map(function(x, y) { return x + y } );

    alert(x);
</script>

Will this code succeed or fail? and if it succeeds, what is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The final result is [1, 3, 5, 7]. Let’s understand why we will have this result. The main idea of the previous expression is to understand how Array.prototype.map works.

According to ECMA documentation, Array.prototype.map creates a new array with the results of calling a provided function on every element in this array; this provided function represents the first parameter. This means that the following function will be called on every element in the array:

function(x, y) { return x + y } 

Array.prototype.map passes the array element and its index to the provided function; this means that the resulting array will be as follows:
[1 + 0, 2 + 1, 3 + 2, 4 + 3] ==> [1, 3, 5, 7].

Preventing anchors from scrolling to top

You may experience when clicking an anchor (which may be styled as a button) that the web page scrolls to the top which may be an un-desirable behaviour for the end user who is using the page.

For example, assume that we have the following simple page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <title>test</title>
  </style>
</head>
<body>
    <p>Some elements here that cause the page to scroll</p>
    
    <a id="save" href="#">Do some Ajax operation</a>
    
    <script>
        document.getElementById('save').onclick = function(event) {
            alert("do some Ajax operation");
        };
    </script>

</body>
</html>

In order to stop this annoying behavior, you need to prevent the default behavior of the anchor by using event.preventDetfault() or event.returnValue = false for the browsers that does not support preventDefault() as follows:

...
<script>
    document.getElementById('save').onclick = function(event) {
        event.preventDefault ? event.preventDefault() : event.returnValue = false;
            
        alert("do some Ajax operation");
            
        return false;
    };
</script>
...

This is all about the trick.

Fast checking for Empty Objects in JavaScript

It is a very common requirement that is needed by many JavaScript developers to check if an object is empty in JavaScript without having to write more than one line of code. In the old days, you usually had to make the following for … loop in a common function isEmpty in order to check if the object is empty:

function isEmpty(myObject) {
    for(var key in myObject) {
        if (myObject.hasOwnProperty(key)) {
            return false;
        }
    }

    return true;
}

Thanks to ECMAScript 5, you can now just use the Object.keys() function to check the object keys, so you can check if the myObject (for example) is empty as follows:

Object.keys(myObject).length == 0

JavaScript Quiz #8 (One line Quiz)

Assume that we have the following short JavaScript code:

<script>
    var result = (2..valueOf() + ({z : 10, x : 20}).x);
    alert(result);
</script>

Will this code succeed or fail? and if it succeeds, what is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The final result is 22. Let’s understand why we will have this result. Let’s divide the expression in two parts. In the first part, we have:

2..valueOf()

This expression will work fine because in JavaScript, it is valid to trail decimal points in float numbers, so for example 2 can be represented as 2 or 2.0 or 2. (without having to mention the extra 0 after the decimal dot).
So the expression can be read simply as (2.).valueOf() which will return 2.

The second part is straightforward:

({z : 10, x : 20}).x

We have here a JavaScript object with two attributes x and z, and we are getting the value of x using .x, which means that the result will be equal to x value which is 20.

Adding the first part result to the second part result will result in: 20 + 2 = 22.

JavaScript Quiz #7

Assume that we have the following short JavaScript code:

<script>
    var str = new String("Hello");
	
    var result = typeof(str instanceof String);
    alert(result); //What is the output of the alert? 
	
    result = typeof typeof(str instanceof String);
    alert(result); //What is the output of the alert? 
	
    result = typeof typeof typeof(str instanceof String);
    alert(result); //What is the output of the alert? 	
</script>

What is the output of each alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The result will be as follows boolean then string then string. Let’s understand why we have these results. In the first expression (which is a very straightforward):

var result = typeof(str instanceof String);

Will executed as follows:
1. str instanceof String will return true.
2. typeof (true) will return "boolean".

In the second expression:

var result = typeof typeof(str instanceof String);

Why does result will be string, this is because the expression will be executed as follows:
1. str instanceof String will return true.
2. typeof (true) will return "boolean" as you notice here typeof(true) returns a String that contains “boolean” value. It is important to know that JavaScript typeof operator always returns String.
3. Finally, it is now clear that typeof ("boolean") will return "string".

In the third expression:

var result = typeof typeof typeof(str instanceof String);

It is much similar to the second expression, result will return “string” because the third expression will be executed as follows:
1. str instanceof String will return true.
2. typeof (true) will return "boolean".
3. typeof ("boolean") will return "string".
3. Finally, typeof ("string") will return "string".

So now you can guess what is the result of ;):

alert(typeof typeof typeof typeof typeof typeof typeof(str instanceof String));

The best selling Amazon DE #13 Web Programming book

I would like to thank all the readers of “JavaScript Unit Testing” book, thanks to them the book is currently #13 best selling web programming in Amazon DE. I really hope that all of them find what they were looking for in my humble book.

JavaScript Unit Testing book is one of the best selling books in Amazon DE

JavaScript Unit Testing book is one of the best selling books in Amazon DE