From e81238bf93dfe22d9c434635231e45adc47221e5 Mon Sep 17 00:00:00 2001 From: Jeffrey Heer Date: Fri, 27 May 2016 16:24:58 -0700 Subject: [PATCH] Add ordinal invert. --- src/ordinal.js | 13 ++++++++++++- test/ordinal-test.js | 10 ++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/ordinal.js b/src/ordinal.js index e267169..f1f6bf4 100644 --- a/src/ordinal.js +++ b/src/ordinal.js @@ -5,6 +5,7 @@ export var implicit = {name: "implicit"}; export default function ordinal() { var index = map(), + invIndex = null, domain = [], range = [], unknown = implicit; @@ -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; @@ -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) diff --git a/test/ordinal-test.js b/test/ordinal-test.js index cc9ccf6..f3fe9b0 100644 --- a/test/ordinal-test.js +++ b/test/ordinal-test.js @@ -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(); +});