1.1.1 • Published 9 years ago

kasai v1.1.1

Weekly downloads
4
License
LGPL-3.0
Repository
github
Last release
9 years ago

Kasai

A pattern matching library for TypeScript (and JavaScript)

Pattern matching allows for concise logic based on the value and shape of data.

Kasai provides an intuitive interface for pattern matching in TypeScript and JavaScript.

Importing Kasai (TypeScript)

/// <reference path='node_modules/kasai/target/types' />
import kasai = require('kasai');

Matching

Pattern matching is really great for inspecting complex data structures with ease.

How many times have you written code like this?

let shippingDestination = (user) => {
    return user.hasOwnProperty('contactInfo')
        && user.contactInfo.hasOwnProperty('address')
        && user.contactInfo.address.hasOwnProperty('zip')
        && user.contactInfo.address.zip.length === 5
        ? 'domestic'
        : 'foreign';
}

Yuck!

With Kasai, that mess becomes this:

let shippingDestination = (user) => {
    return match(user, [
        [{ contactInfo: { address: { zip: (z) => z.length === 5 } } }, 'domestic'],
        [_, 'foreign']
    ]);
}

The concise, declarative syntax makes this code easier to read and easier for others to understand.

Kasai has support for matching any combination of objects, arrays, and primitive types (including circular references).

Capturing

Kasai also allows you to capture values from within a data structure with $.

let users = [
    { first: 'Thomas', middle: 'Alva', last: 'Edison' },
    { first: 'Nikola', last: 'Tesla' }
];

let getFullName = (user) => {
    return match(user, [
        [{first: $, middle: $, last: $}, (f, m, l) => f + ' ' + m + ' ' + l],
        [{first: $, last: $}           , (f, l) => f + ' ' + l],
        [_, 'unknown']
    ]);
}

let fullNames = users.map(getFullName);
// >>  ['Thomas Alva Edison', 'Nikola Tesla']

When Conditions

When conditions allow you to augment a pattern by comparing captured values.

let pallet = { items: 100, itemWeight: 1, isHazardous: true }

let isHeavy = (n, w) => n * w > 50;

let rate = match(pallet, [
    [{ isHazardous: true, items: $, itemWeight: $}, when(isHeavy), 100],
    [{ isHazardous: false, items: $, itemWeight: $}, when(isHeavy), 75],
    [{ isHazardous: true }, 90],
    [_, 50]
]);

rate === 100 // true

For more examples, see the docs folder.

1.1.1

9 years ago

1.1.0

9 years ago

1.0.3

9 years ago

1.0.2

9 years ago

1.0.1

9 years ago

1.0.0

9 years ago

0.0.2

9 years ago

0.0.1

9 years ago