npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sparkler

v0.3.5

Published

Native pattern matching for JavaScript

Downloads

109

Readme

sparkler

Sparkler is a pattern matching engine for JavaScript built using sweet.js macros, so it looks and feels like native syntax. It has no runtime dependencies and compiles down to simple ifs and fors.

Here's a small slice of what you can do with it:

function myPatterns {
  // Match literals
  42 => 'The meaning of life',

  // Tag checking for JS types using Object::toString
  a @ String => 'Hello ' + a,

  // Array destructuring
  [...front, back] => back.concat(front),

  // Object destructuring
  { foo: 'bar', x, 'y' } => x,

  // Custom extractors
  Email { user, domain: 'foo.com' } => user,

  // Rest arguments
  (a, b, ...rest) => rest,

  // Rest patterns (mapping a pattern over many values)
  [...{ x, y }] => _.zip(x, y),

  // Guards
  x @ Number if x > 10 => x
}

You can see a slew of more examples in the pattern spec file

Install

npm install -g sweet.js
npm install sparkler
sjs -m sparkler/macros myfile.js

How Does It Work?

Sparkler overloads the function keyword as a macro (don't worry, all your old functions will still work) but implements a slightly different syntax. There's no argument list after the name or function keyword. Instead the function body is just a set of ES6 style arrow-lambdas separated by commas.

function myFunc {
  // Single arguments don't need parens and simple expression 
  // bodies get an implicit `return`.
  a @ String => 'Hello ' + a,

  // Add parens and braces if you need more.
  (x, y, z) => {
    return x + y + z;
  }
}

You can also do this with anonymous functions:

DB.getResource('123', function {
  (null, resp) => complete(resp),
  (err) => handleError(err)
})

If no case matches, a TypeError('No match') is thrown.

Optimization

Sparkler doesn't just try each case one at a time until one passes. That would be really inefficient. Instead, it analyzes your entire pattern matrix, and rearranges things as needed to get an optimized set of tests while still preserving the left-to-right, top-down semantics.

function expensiveExtraction {
  (MyExtractor(x, y, z), 1) => doThis(),
  (MyExtractor(x, y, z), *) => doThat()
}

Let's say MyExtractor is really expensive. Sparkler efficiently backtracks, so it will only get called once in this set of tests.

Argument Length

In JavaScript, you can call a function with any number of arguments. Arguments that are not provided are just set to undefined. Sparkler does not implicitly match on argument length.

function ambiguous {
  (a)       => 1,
  (a, b)    => 2,
  (a, b, c) => 3
}

The above function will always return 1 no matter how many arguments you call it with as the first case always matches. The subsequent cases are actually removed from the final output in the optimization phase.

If you want to match on specific argument length, you need to add a guard to your case.

function argCheck {
  // Using arguments.length
  (a, b, c) if arguments.length == 3 => 1,
  // Or matching undefined
  (a, b, undefined) => 2,
  (a) => 1
}

The only time Sparkler is strict with argument length is with the empty parameter list (). It will check that arguments.length is zero. This is so you can do stuff like this:

Foo.prototype = {
  // jQuery-style getter/setter
  val: function {
    ()  => this._val,
    val => {
      this._val = val;
      return this;
    }
  }
}

If you want a catch-all, you should use a wildcard (*) or default instead.

Match Keyword

Sparkler exports a match macro for doing easy matching in any position.

Match Expressions

Match expressions look like function matching, except you provide the argument(s) upfront.

var num = 12;
var isNumber = match num {
  Number => true,
  *      => false
};

This works by desugaring match into a self-invoking function with num as the argument. Consequently, match expressions do not support break, continue, and early return. Using a match expression in statement position will result in a parse error.

Match Statements

Match statements use a slightly different syntax. They look like a suped up switch.

var a = Foo(Foo(Foo(42)));
while (1) {
  match a {
    case Foo(inner):
      a = inner;
    default:
      break;
  }
}

Unlike switches, cases in a match statement do not fall through. Early return, break, and switch are all supported. Using a match statement in expression position will result in a parse error.

Multiple Matches

You can match on multiple expressions at once in both match expressions and statements.

var allNums = match (num1, num2, num3) {
  (Number, Number, Number) => true,
  *                        => false
};

match (num1, num2, num3) {
  case (Number, Number, Number):
    allNums = true;
  default:
    allNums = false;
}

Pattern Bindings and Hoisting

All bindings in patterns are declared as vars by default, as it is the most widely supported declaration form. Consequently, they will hoist outside of match statements. You may specify your declaration form by prefixing pattern bindings with one of var, let, or const.

match x {
  case Foo(a):       ... // will hoist
  case Foo(var a):   ... // will hoist
  case Foo(let a):   ... // will not hoist
  case Foo(const a): ... // will not hoist, immutable
}

Custom Extractors

You can match on your own types by implementing a simple protocol. Let's build a simple extractor that parses emails from strings:

var Email = {
  // Factor out a matching function that we'll reuse.
  match: function {
    x @ String => x.match(/(.+)@(.+)/),
    *          => null
  },

  // `hasInstance` is called on bare extractors.
  hasInstance: function(x) {
    return !!Email.match(x);
  },

  // `unapply` is called for array-like destructuring.
  unapply: function(x) {
    var m = Email.match(x);
    if (m) {
      return [m[1], m[2]];
    }
  },

  // `unapplyObject` is for object-like destructuring.
  unapplyObject: function(x) {
    var m = Email.match(x);
    if (m) {
      return {
        user: m[1],
        domain: m[2]
      };
    }
  }
};

Now we can use it in case arguments:

function doStuffWithEmails {
  // Calls `unapplyObject`
  Email { domain: 'foo.com' } => ...,
  
  // Calls 'unapply'
  Email('foo', *) => ...,

  // Calls `hasInstance`
  Email => ...
}

If you don't implement hasInstance, Sparkler will fall back to a simple instanceof check.

adt-simple

adt-simple is a library that implements the extractor protocol out of the box, and even has its own set of macros for defining data-types.

var adt = require('adt-simple');
union Tree {
  Empty,
  Node {
    value : *,
    left  : Tree,
    right : Tree
  }
} deriving (adt.Extractor)

function treeFn {
  Empty => 'empty',
  Node { value @ String } => 'string'
}

Optional Extensions

Sparkler also provides a small library that extends some of the native types with convenient functions.

require('sparkler/extend');

// Date destructuring
function dateStuff {
  Date { month, year } => ...
}

// RegExp destructuring
function regexpStuff {
  RegExp { flags: { 'i' }} => ...
}

// Partial-function composition with `orElse`
function partial {
  Foo => 'foo'
}

var total = partial.orElse(function {
  * => 'anything'
})

orElse is added to the prototype safely using defineProperty and isn't enumerable.


Author

Nathan Faubion (@natefaubion)

License

MIT