[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].

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));

JavaScript Quiz #6

Assume that we have the following short JavaScript code:

<script>
	var result = [12 + 21]['valueOf']()['length'];
	alert(result); //What is the output of the alert?

	result = [12 + 21]['valueOf']['length'];
	alert(result); //What is the output of the alert? 
</script>

What is the output of each alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The result will be as follows 1 then 0. The first expression (the easy one) will be executed as follows:

var result = [12 + 21]['valueOf']()['length'];

The expression can be read as [33].valueOf().length which means that .length property will print the length of the valueOf() call to array [33] which is 1. Note that the [33].valueOf will return [33].

The second expression is the tricky part:

var result = [12 + 21]['valueOf']['length'];

The expression can be read as follows [33].valueOf.length. This is really completely different from the first expression because in this case the .length property will print the number of arguments of the valueOf method which is zero. This is because if the .length property is attached to a method then it will print the number of arguments of the method.

JavaScript Quiz #5

This quiz covers some of the JavaScript operators in order to explain they can work together inside expressions. Assume that we have the following JavaScript code:

var object1 = {
    valueOf: function () {
	return 10;
    },
    toString: function () {
	return "object1";
    }
};

var object2 = {
    valueOf: function () {
	return 20;
    },
    toString: function () {
	return "object2";
    }
};

var object3 = {
    valueOf: function () {
	return 30;
    },
    toString: function () {
	return "object3";
    }
};

var result = (object2, object1, object3) + object1 +-- object1; 
alert(result);

What is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The output of the alert is 49. Let’s analyze this quiz. In the following expression:

(object2, object1, object3)

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
(object2, object1, object3) will be evaluated to object3. We will then have the following reduced expression:

object3 + object1 +-- object1

In this expression, we have two main operators:
1. + operator.
2. — prefix operator.

The execution order will be as follows:
1. — prefix operator.
2. + operator.

To get the complete list of operator precedence, check https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence.

The execution order means that the expression evaluation will start by:

-- object1

The — prefix operator will be applied on object1 which will result in calling the valueOf method of object1, This means that the result will be 10 – 1 = 9.

Then the evaluation execution continues by adding object3 + object1 to the previous result as follows:

object3 + object1 + 9

Now, we come to the simplest part of the quiz, the valueOf methods of object1 and object3 are called, which means that the final result will be 30 + 10 + 9 = 49.

The original addition rule according to Ecma-262 specification is as follows for your reference:
“The addition operator either performs string concatenation or numeric addition.

The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:
1. Let lref be the result of evaluating AdditiveExpression.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating MultiplicativeExpression.
4. Let rval be GetValue(rref).
5. Let lprim be ToPrimitive(lval).
6. Let rprim be ToPrimitive(rval).
7. If Type(lprim) is String or Type(rprim) is String, then
a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).

In order to check previous quizzes:
1. JavaScript Quiz #4
2. JavaScript Quiz #3
3. JavaScript Quiz #2
4. JavaScript Quiz #1

JavaScript Quiz #4

Understanding JavaScript by example is useful for absorbing the different concepts of the language quickly. In this post, I will illustrate a JavaScript Quiz to understand how the JavaScript operators work together. Assume that we have the following JavaScript code:

var object1 = {
    valueOf: function () {
        return 1;
    },
    toString: function () {
        return "object1";
    }
};

var object2 = {
    valueOf: function () {
        return 2;
    },
    toString: function () {
        return "object2";
    }
};

alert((object2 > object1 +-- object1) + true); //What is the output of the alert?

What is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The output of the alert is 2. In order to understand why we have this result, we should know how the different JavaScript operators work together. Let’s analyze this quiz.
In the following expression:

(object2 > object1 +-- object1) + true

We have two main part, the first part is the expression between brackets and the second one is the boolean true operand. Let’s see how the first part will be evaluated.

object2 > object1 +-- object1

In this expression, we have three main operators:
1. > operator.
2. + operator.
3. — prefix operator.

The execution order will be as follows:
1. — prefix operator.
2. + operator.
3. > operator.

To get the complete list of operator precedence, check https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence.

The execution order means that the expression evaluation will start by:

-- object1

The — prefix operator will be applied on object1 which will result in calling the valueOf method of object1, which means that the result will be 1 – 1 = 0.

Then the evaluation continues by adding object1 to the previous result:

object1 + 0

The valueOf method of object1 is called again, which means that the result will be 1 + 0 = 1.

Then the comparison will be performed as follows:

object2 > 1

In order to perform the comparison, the valueOf method of object2 is called, which means that the result will be 2 > 1 = true.

Then finally we will have the following:

true + true

According to Ecma-262, if we have an arithmetic plus operator and none of its operand are of type String, then both operands will be converted to numeric and the addition operation is performed. In JavaScript when true is converted to Numeric, the result will be 1 (while false is converted to 0).

The original addition rule according to Ecma-262 specification is as follows for your reference:
“The addition operator either performs string concatenation or numeric addition.

The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:
1. Let lref be the result of evaluating AdditiveExpression.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating MultiplicativeExpression.
4. Let rval be GetValue(rref).
5. Let lprim be ToPrimitive(lval).
6. Let rprim be ToPrimitive(rval).
7. If Type(lprim) is String or Type(rprim) is String, then
a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).