Fractional Indexing
This is a Haxe port of fractional-indexing, based on Implementing Fractional Indexing by David Greenspan.
Fractional indexing is a technique to create an ordering that can be used for Realtime Editing of Ordered Sequences.
This implementation includes variable-length integers, and the prepend/append optimization described in David's article.
Usage
between
Generate a single key in between two points.
class Example {
static function main() {
var first = FractionalIndexing.between(null, null); // "a0"
// Insert after 1st
var second = FractionalIndexing.between(first, null); // "a1"
// Insert after 2nd
var third = FractionalIndexing.between(second, null); // "a2"
// Insert before 1st
var zeroth = FractionalIndexing.between(null, first); // "Zz"
// Insert in between 2nd and 3rd (midpoint)
var secondAndHalf = FractionalIndexing.between(second, third); // "a1V"
}
}
nBetween
Use this when generating multiple keys at some known position, as it spaces out indexes more evenly and leads to shorter keys.
class Example {
static function main() {
var first = FractionalIndexing.nBetween(null, null, 2); // ['a0', 'a1']
// Insert two keys after 2nd
var next = FractionalIndexing.nBetween(first[1], null, 2); // ['a2', 'a3']
// Insert two keys before 1st
var prev = FractionalIndexing.nBetween(null, first[0], 2); // ['Zy', 'Zz']
// Insert two keys in between 1st and 2nd (midpoints)
var mids = FractionalIndexing.nBetween(first[0], first[1], 2); // ['a0G', 'a0V']
}
}
Sorting
The indexes generated by this library are case-sensitive and should be sorted using standard string comparison.
var arr = [
{ id: "todo_1", fractionalIndex: "YzZ" },
{ id: "todo_2", fractionalIndex: "Yza" }
];
arr.sort((a, b) -> Reflect.compare(a.fractionalIndex, b.fractionalIndex));
Installation
haxelib install fractional-indexing
-lib fractional-indexing
Development
Run tests (requires utest haxelib):
haxe test.hxml