These problems assume you have Firefox and Firebug installed. The
problems are designed so you can work through them incrementally while going
through the tutorial.
- Write the factorial function JavaScript: fact(0) == 1 && fact(n) == n*fact(n-1)
- Write a curried version of addition: add(1)(2) == 3
- Write a variable-arity addition function: sum() == 0 && sum(1, 2, 3) == 6 && sum(4, 6, 1, 2, -8) == 5
- Write the bind function: bind(obj, obj.method)(arg) == obj.method(arg)
- The following program has a scoping problem. We'd like it to
alert 1, then 2, and then 3; but instead it alerts 3 three times.
How can you fix it?
for (var i = 0; i < 3; i++) {
setTimeout(function () {
alert(i);
}, i * 200);
}
(Borrowed from http://ejohn.org/apps/learn/#62)
- Modify Object.prototype so that all objects have
an "identify()" method where the effect of
obj.identify() is alert(obj).
For example, "(3).identify()" should open an alert
window saying "3".
- Write a function of one argument which raises an exception
(only) when the argument is an odd number. For example:
- f(null) → no exception
- f(2) → no exception
- f(3) → exception!
- Write a variant of the apply() method of function
objects which, in the case of an exception, catches and
returns the exceptions (or otherwise, returns the normal
function result).
Make your new method available as an applySilently()
method of all functions. Example usage:
function f(x, y) {
throw { this: this, name: 'f', sum: x+y };
}
var result = f.applySilently(null, [1, 2]);
result.this == null
&& result.name == 'f';
- Write and install a callSilently() method analogous
to applySilently(). Example usage:
var result = f.callSilently(null, 1, 2);
result.this == null
&& result.name == 'f';
- Save SomePackage.js and OtherPackage.js to
files, and write an index.html file which loads
package.js, defines a package requiring
OtherPackage.js and demonstrates that the packages
were loaded properly by running the following code:
otherObject.put('test', 2, 3);
alert(otherObject.get('test'));
(See here
for the code of SomePackage.js and
OtherPackage.js)