Skip to content
master
Go to file
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 

readme.md

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.

About

A pattern matching library

Resources

License

Releases

No releases published

Packages

No packages published
You can’t perform that action at this time.