JavaScript tutorial problems

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.

  1. Write the factorial function JavaScript: fact(0) == 1 && fact(n) == n*fact(n-1)
  2. Write a curried version of addition: add(1)(2) == 3
  3. Write a variable-arity addition function: sum() == 0 && sum(1, 2, 3) == 6 && sum(4, 6, 1, 2, -8) == 5
  4. Write the bind function: bind(obj, obj.method)(arg) == obj.method(arg)
  5. 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)
  6. 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".
  7. Write a function of one argument which raises an exception (only) when the argument is an odd number. For example:
  8. 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';
    
  9. Write and install a callSilently() method analogous to applySilently(). Example usage:
    var result = f.callSilently(null, 1, 2);
       result.this == null
    && result.name == 'f';
    
  10. 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')); // Should display 21
    
    (See here for the code of SomePackage.js and OtherPackage.js)