jPaq Example - 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 same. This is where the curry() function comes in handy.

Let's use a simple example.  Let's say that we have a function whose first parameter is a boolean value, the second is an array of strings, and the third is the string to be tested.  If the first parameter evaluates to true, the function returns the number of strings in the second parameter that were found in the third parameter.  If the first parameter evaluates to false, the function returns a boolean value indicating whether or not all of the strings in the array were found in the third parameter.  The issue is, we have a new project that needs two functions:

  1. One that will return the number of substring matches for an arbitrary string but a specific array.
  2. One that will return a boolean value indicating whether or not all of the strings in a specific array were found in an arbitrary string.

Instead writing two new functions, we can use curry to create two new functions on the fly.  The code below illustrates this very situation:

Applicable Parts

Related Examples

  1. Finding & Replacing with Wildcards
    The following shows you how to search strings by using wildcards and even how to replace what you find: alert("Where in the world is…
  2. Counting Squares On A Checker Board
    How many squares are there on a checker board?  Most people would say there are only 64 squares, but others would say what about…
  3. 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…
  4. Wildcard Expression Tester
    Many people know how to write wildcard searches (or wildcard expressions), but a lot less people know how to write regular expressions.  If you…
  5. Cartesian Product
    A few weeks ago, I came across a question about finding the cartesian product of two or more arrays in JavaScript.  The following is…