Skip to content
A pattern-matching function constructor
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


Brian Carstensen

I learned of the concept of pattern-matching functions while thumbing through The Blackstag Blog's Guide to Programming in Clojure for Beginners.

At the time, I was working on a sort of catch-all function for something at work, where it would do something a bit different depending on the number and types of the arguments it's given. A pattern matching function would have been a pretty elegant solution, so I tried toimplement one in JavaScript.

Basically you instantiate a new PatternedFunction with a series of arrays of constructors, with each array representing a possible set of arguments, and functions. Each array it finds will be a pattern for the function that follows, and you can have any number of arrays before each function. For example:

whatIsThis = new PatternedFunction(
    function() {
        console.log('That was a boolean.');

    function() {
        console.log('That was either a string or a number.');

    [String, Number],
    function() {
        console.log('Those were a string AND a number.');

    function() {
        console.log('I have no idea what that was.');

Note that final empty array, which indicates that the function that follows it should match any argument set that falls through the patterns.

You can also use a couple wild card strings: "*" for any type or value, and "..." as the last argument to indicate that anything from that point on should be ignored when matching.

whatElse = new PatternedFunction(
    [String, '*'],
    function() {
        console.log('That was a string and something else.');

    ['*', Function, '...'],
    function() {
        console.log('The second argument was a function, that\'s all I know.');

I think it's kinda neat.

Something went wrong with that request. Please try again.