Skip to content

Instantly share code, notes, and snippets.

@brigand
Last active January 9, 2021 16:09
Show Gist options
  • Save brigand/ed98ddea1c5571b4ca45 to your computer and use it in GitHub Desktop.
Save brigand/ed98ddea1c5571b4ca45 to your computer and use it in GitHub Desktop.
ImmutableJS macros for SweetJs

These macros are designed to provide a literal notation for immutable-js using sweetjs.

The most interesting being the Map literal

var map = im{"foo": "bar", "baz": "quux"};

This compiles to the 2d array version of Immutable.Map.

var map = Immutable.Map([
   ["foo", "bar"],
   ["baz", "quux"]
]);

This means that the following is also perfectly valid.

var user1 = {name: "John"};
var book1 = {name: "Cat in the Hat"};

var favoriteBooks = im{user1: book1};

It also means that strings must be quoted, so... use jshint with undef on :-)

Here's some other examples. I'd explain them, but if I need to then these macros have failed.

var map = im{"foo": "bar", "baz": "quux"};
var orderedMap = im:ordered{"foo": "bar", "baz": "quux"};
var list = im["foo", "bar", "baz"];
var stack = im:stack["foo", "bar", "baz"];
var set = im:set["foo", "bar", "baz"];
var record = im:record {"foo": "bar", "baz": "quux"};

// complex object
var person = im{
  "name": "John Doe",
  "hobbies": im:set[
  	"hiking",
	"art"
  ],
  "relationships": im{
    people["Jane"]: "wife"
  }
};

For stylistic variations feel free to put a space before 'im', and wrap keys like user1 in parentheses.

macro im {
// Map
rule {
{$pair:( $key:expr : $value:expr ) (,) ...}
} => {
Immutable.Map([ $( [ $pair$key, $pair$value ] ) (,) ... ])
}
// OrderedMap
rule {
:ordered{$pair:( $key:expr : $value:expr ) (,) ...}
} => {
Immutable.OrderedMap([ $( [ $pair$key, $pair$value ] ) (,) ... ])
}
// List
rule {
[$value:expr (,) ...]
} => {
Immutable.List.of( $value (,) ... )
}
// Stack
rule {
:stack[$value:expr (,) ...]
} => {
Immutable.Stack.of( $value (,) ... )
}
// Set
rule {
:set[$value:expr (,) ...]
} => {
Immutable.Set.of( $value (,) ... )
}
// Record
rule {
:record $obj:expr
} => {
Immutable.Record($obj)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment