valiant

JavaScript interval arithmetic library

Usage no npm install needed!

<script type="module">
  import valiant from 'https://cdn.skypack.dev/valiant';
</script>

README

valiant

semantic-release Build Status

JavaScript interval arithmetic library.

An interval represents a range of data with an associated sort function that defines how values relate to each other. For example, a range of numbers just uses subtraction.

Intervals can have inclusive or exclusive bounds, and you can define a custom sort function.

For more, see Wikipedia. This library is largely inspired by the Haskell's Data.Interval and was built originally to manage lists of Tweets within TweetDeck.

Install

npm install --save valiant

Use

To make an Interval, you need to create a constructor:

import { createInterval } from 'valiant';

const Interval = createInterval();

By default it will manage integers:

// (0,100] — the numbers 0 to 100, excluding 0
new Interval(
    Interval.exclusiveEndpoint(0),
    Interval.inclusiveEndpoint(100)
)

You can provide a custom sort function to support a different data type:

const DateInterval = createInterval(function sortDates(a, b) {
    return a.getTime() - b.getTime();
});

// [12 hours ago,now] — 12 hours ago until now
new DateInterval(
    DateInterval.incEnd(
        new Date(Date.now() - (1000 * 60 * 60 * 12))
    ),
    DateInterval.incEnd(
        new Date(Date.now())
    )
)

You can do calculations with two intervals:

i = [1,3]
j = [2,4]
k = [5,6]

i.intersection(j)         // [2,3]
i.hull(j)                 // [1,4]
i.contiguousWith(j)       // true
i.unify(j)                // [1,4]

i.intersection(k)         // Interval.empty
i.hull(k)                 // [1,6]
i.contiguousWith(k)       // false
i.unify(k)                // Interval.empty

i.equalTo(j)              // false
i.contains(2)             // true
i.isSubsetOf(j)           // false

If there is no possible unification, the empty set (Interval.empty) results.

There are two special intervals:

Interval.empty // {}
Interval.whole // (-Infinity, Infinity)

You can also create an interval of value:

Interval.singleton(5) // [5,5]

To get Haskelly for a bit, because of the closed-over sort function, Interval is a bit like a typeclass with an Ordinal type constraint:

data Ord a => Interval a = Interval (EndPoint a, Bool) (Endpoint a, Bool)

Why?

TweetDeck uses this library to manage lists of many kinds of data (we call them chirps). With it we detect overlapping blocks of Tweets, gaps and do neat memory management optimisations.

Development

$ npm install
$ npm test

Commit messages should follow the Angular commit message guidelines.

Release

This repository uses semantic-release. Changes will automatically be released to npm.