Skip to content

Instantly share code, notes, and snippets.

@hallettj
Created September 10, 2013 23:26
Show Gist options
  • Save hallettj/6517169 to your computer and use it in GitHub Desktop.
Save hallettj/6517169 to your computer and use it in GitHub Desktop.
Slides from my presentation on Mori, a library that makes data structures from the ClojureScript standard library available to plain JavaScript apps.

Mori is not an island

http://swannodette.github.io/mori/

Persistent data structures

var emptyVec = mori.vector();

var nonEmpty = mori.conj(emptyVec, 1, 2, 3, 4);

var nonEmpty_ = mori.subvec(nonEmpty, 1, 3);

mori.reduce(mori.sum, 0, nonEmpty_);  // 5

Data structures available

  • list
  • vector
  • array_map
  • hash_map
  • range
  • set
  • sorted_map
  • sorted_map_by
  • sorted_set
  • sorted_set_by

range

var numbers = mori.range();
var nats    = mori.drop(1, numbers);

mori.take(10, nats);  // (1 2 3 4 5 6 7 8 9)

mori.into_array(mori.take(10, nats));  // [1 2 3 4 5 6 7 8 9]

set

var s = mori.set([1, 2, 3, 4]);

mori.has_key(s, 3);  // true

sorted_set_by

var empty = mori.sorted_set_by(function(a, b) {
    return a.foo - b.foo;
});

var s = mori.conj(empty, {foo: 2, msg: 'second'}, {foo: 1, msg: 'first'});

mori.first(s).msg;  // 'first'

Documentation

http://clojuredocs.org/clojure_core/clojure.core/sorted-set-by

Complies with AMD and CommonJS

$ npm install mori

require(['mori'], function(mori) {
    // ...
});

var mori = require('mori');

Node lookup in a distributed hash table

function findNode(idSelf, routeTable, concurrencyLvl, runQuery, target) {
    var startPeers = routeTable.closest(target).slice(0, concurrencyLvl);
    var complete   = false;

    var state = mori.into(mori.sorted_set_by(function(a, b) {
        return Id.compare(Id.dist(target, a.id), Id.dist(target, b.id));
    }), startPeers);

    var threads = startPeers.map(thread);
    function thread() {
        var closest = mori.first(state);
        state = mori.drop(1, state);

        if (!closest || complete) {
            return Bacon.never();
        }
        if (Id.compare(closest.id, target) === 0) {
            complete = true;
            return Bacon.once(closest);
        }
        return Bacon.merge(
            Bacon.once(closest),
            Bacon.fromPromise(
                runQuery(closest, messages.find_node(idSelf, target))
            )
            .flatMap(function(resp) {
                state = mori.into(resp.results);
                return thread();
            })
        );
    }
    return Bacon.mergeAll(threads);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment