feat: getter function to return color mapping (#124)

This commit is contained in:
Kim Truong 2019-03-25 14:33:45 -07:00 committed by Yongjie Zhao
parent e8e54adad9
commit 9dd30b0350
2 changed files with 34 additions and 0 deletions

View File

@ -57,4 +57,22 @@ export default class CategoricalColorScale extends ExtensibleFunction {
return this;
}
/**
* Get a mapping of data values to colors
* @returns an object where the key is the data value and the value is the hex color code
*/
getColorMap() {
const colorMap: { [key: string]: string } = {};
const { length } = this.colors;
Object.keys(this.seen).forEach(value => {
colorMap[value] = this.colors[this.seen[value] % length];
});
return {
...colorMap,
...this.forcedColors,
...this.parentForcedColors,
};
}
}

View File

@ -83,6 +83,22 @@ describe('CategoricalColorScale', () => {
expect(scale).toBe(output);
});
});
describe('.getColorMap()', () => {
it('returns correct mapping and parentForcedColors and forcedColors are specified', () => {
const scale1 = new CategoricalColorScale(['blue', 'red', 'green']);
scale1.setColor('cow', 'black');
const scale2 = new CategoricalColorScale(['blue', 'red', 'green'], scale1.forcedColors);
scale2.setColor('pig', 'pink');
scale2.getColor('cow');
scale2.getColor('pig');
scale2.getColor('horse');
expect(scale2.getColorMap()).toEqual({
cow: 'black',
pig: 'pink',
horse: 'blue',
});
});
});
describe('a CategoricalColorScale instance is also a color function itself', () => {
it('scale(value) returns color similar to calling scale.getColor(value)', () => {
const scale = new CategoricalColorScale(['blue', 'red', 'green']);