JavaScript Exercise #4 - Minimum Number of Stamps

I read about closure in JavaScript over the weekend. The book defined it as where “inner functions get access to the parameters and variables of the functions they are defined within with the exception of this and arguments,” (Crockford, 37). One application of closure is for implementing memoization algorithms. You can easily hide the memoized table in the same function object as your basic recursive function.

Today’s exercise is a classic dynamic programming puzzle. Given a postage and a set of stamp prices, compute the minimum number of stamps you need to buy for the postage. For example, suppose your postage is 32 cents, and the stamp prices available are 30, 2, and 1 cents. Then your answer should be two stamps. This is how you use this function.


JavaScript Exercise #3 - Reverse Words in Sentence

I have prepared yet another string manipulation exercise for today. The goal this time is to use the apply invocation pattern (Crockford, 30) and the array-like arguments object (Crockford, 31).

apply takes two arguments: the first argument overrides this and the second one is an array of arguments for the function applied. Note here that the default arguments object has a length method and you can access individual argument with brackets; however, it does not have other standard array features, such as push or pop.

Here is a modified version of yesterday’s code that produces the same result.


JavaScript Exercise #2 - Reverse String

Yet another standard coding exercise. I wanted to try the function invocation pattern (Crockford, 28), and so I created the following code. Not noted here, the inner function swap cannot access this directly. By convention you set a variable that to reference this and use that in the inner function instead of this (Crockford, 29).

Alternatively, there is a shorter version of string reverse for JavaScript on Comparison of programming languages (string functions).


JavaScript Exercise #1 - Fibonacci Number

I started reading Crockford’s book on JavaScript some time ago, and decided to help myself warming up to JavaScript by doing some coding exercises. Here is a generic recursive solution for nth Fibonacci number generator. Notice the C-like syntax.


Functions are objects. You can easily create a field for a function and access the property value with the dot operator and property name. The default return value of an object is undefined, except for constructors, where the default is this.