Skip to content

Commit

Permalink
Add ordinal invert.
Browse files Browse the repository at this point in the history
  • Loading branch information
jheer committed May 27, 2016
1 parent 7373ec0 commit e81238b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/ordinal.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export var implicit = {name: "implicit"};

export default function ordinal() {
var index = map(),
invIndex = null,
domain = [],
range = [],
unknown = implicit;
Expand All @@ -14,13 +15,14 @@ export default function ordinal() {
if (!i) {
if (unknown !== implicit) return unknown;
index.set(key, i = domain.push(d));
invIndex = null;
}
return range[(i - 1) % range.length];
}

scale.domain = function(_) {
if (!arguments.length) return domain.slice();
domain = [], index = map();
domain = [], index = map(), invIndex = null;
var i = -1, n = _.length, d, key;
while (++i < n) if (!index.has(key = (d = _[i]) + "")) index.set(key, domain.push(d));
return scale;
Expand All @@ -34,6 +36,15 @@ export default function ordinal() {
return arguments.length ? (unknown = _, scale) : unknown;
};

scale.invert = function(_) {
if (!invIndex) {
invIndex = map();
var n = domain.length;
while (--n >= 0) invIndex.set(range[n], n+1);
}
return domain[invIndex.get(_ + "") - 1];
};

scale.copy = function() {
return ordinal()
.domain(domain)
Expand Down
10 changes: 10 additions & 0 deletions test/ordinal-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,13 @@ tape("ordinal.copy() changes to the range are isolated", function(test) {
test.deepEqual(s2.range(), ["foo", "baz"]);
test.end();
});

tape("ordinal.invert(x) returns first matching domain value", function(test) {
var s = scale.scaleOrdinal().domain(["foo", "bar", "baz", "oof"]).range(["a", "b", "", "a"]);
test.equal(s.invert(), undefined);
test.equal(s.invert("a"), "foo");
test.equal(s.invert("b"), "bar");
test.equal(s.invert(""), "baz");
test.equal(s.invert("c"), undefined);
test.end();
});

0 comments on commit e81238b

Please sign in to comment.