From 3b85a96fddd8fb25e220709e8dcb8ff268d8ded2 Mon Sep 17 00:00:00 2001 From: regorxxx Date: Sun, 10 Mar 2024 11:50:24 +0100 Subject: [PATCH] * fix wrong handling of values outside scale domain due to internal Math.pow usage. See [Issue 331](https://github.com/gka/chroma.js/issues/331) Signed-off-by: regorxxx --- src/generator/scale.js | 4 +++- test/scales.test.js | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/generator/scale.js b/src/generator/scale.js index 8da2e0da..9289794b 100644 --- a/src/generator/scale.js +++ b/src/generator/scale.js @@ -109,7 +109,9 @@ module.exports = function(colors) { t = tMapLightness(t); // lightness correction } - if (_gamma !== 1) { t = pow(t, _gamma); } + if (t > 1) { t = 1; } // pow fails with negative bases, but values are always clamped to the extremes + else if (t < 0) { t = 0 } + else if (_gamma !== 1) { t = pow(t, _gamma); } t = _padding[0] + (t * (1 - _padding[0] - _padding[1])); diff --git a/test/scales.test.js b/test/scales.test.js index ec71979c..ca1043ab 100644 --- a/test/scales.test.js +++ b/test/scales.test.js @@ -275,5 +275,15 @@ vows ) } }, + + 'scale domain': { + topic: { + f: scale(['white','black']).domain([1, 3]).gamma(1.1) + }, + 'should return left color within domain'(topic) { assert.equal(topic.f(1).hex(), '#ffffff'); }, + 'should return right color within domain'(topic) { assert.equal(topic.f(3).hex(), '#000000'); }, + 'should return left color outside domain'(topic) { assert.equal(topic.f(0).hex(), '#ffffff'); }, + 'should return right color outside domain'(topic) { assert.equal(topic.f(4).hex(), '#000000'); } + }, }).export(module);