jPaq Example - Compacting Arrays

The JavaScript library Prototype offers a function which basically removes all of the undefined and null values from the array. Fortunately, JavaScript 1.6 offers a function called Array.prototype.filter() which makes writing this Array.prototype.compact() function of Prototype very simple. Of course, many people are still using old browsers which don't have these function defined; this is where jPaq comes in to play. Since we can be assured that the filter() function exist by using jPaq, we can use the following code to define the compact() function:

Three lines to define this helpful function--that's awesome! Still, I think it would be nice to make this definition even shorter, don't you? Fortunately for us, as long as we are using a build of jPaq which has both Array.prototype.filter() and Function.prototype.curry(), we can use the following one-liner to define the compact() function:

Looking at the above code, you may think that it wouldn't work, but it does. To prove that it works, you can try out the the following executable example:

Applicable Parts

Related Examples

  1. Currying
    At times, you may want to call a function a number of times, but you may notice that the first few arguments are always the…
  2. Currying Up String Functions
    You ever wonder how libraries such as jPaq and Prototype add prototype functions to different classes?  At for jPaq, it isn't by relying…
  3. Flatten Arrays
    One of the nice functions that is provided in Prototype is Array.prototype.flatten().  It gives you the ability to turn arrays such as…