Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[improvement] optimize speed of getCategoricalColorMap (#3178)

Igor Dykhta09297acc0138
diff --git a/src/utils/src/data-scale-utils.ts b/src/utils/src/data-scale-utils.ts
index c0700c110..162d6595f 100644
--- a/src/utils/src/data-scale-utils.ts
+++ b/src/utils/src/data-scale-utils.ts
@@ -382,31 +382,44 @@ export function getCategoricalColorMap(
colors: string[],
domain: (string | number | string[] | number[] | null)[]
): any {
- // colorMap: [string | string[], hexstring]
- const colorToUniqueValues = {};
- const uniqueValues = unique(domain).filter(notNullorUndefined).sort();
- // each unique value assign to a color, the rest unique values assign to last color
- const lastColor = colors[colors.length - 1];
- for (let i = 0; i < uniqueValues.length; ++i) {
- if (i < colors.length) {
- colorToUniqueValues[colors[i]] = uniqueValues[i];
- } else {
- colorToUniqueValues[lastColor] = [
- ...(Array.isArray(colorToUniqueValues[lastColor])
- ? colorToUniqueValues[lastColor]
- : [colorToUniqueValues[lastColor]]),
- uniqueValues[i]
- ];
- }
+ const uniqueValues = unique(domain).sort();
+ const colorMap = colors.map(color => [null, color]);
+
+ if (colors.length === 0 || uniqueValues.length === 0) {
+ return colorMap;
}
- const colorMap = colors.map(color => {
- if (color in colorToUniqueValues) {
- return [colorToUniqueValues[color], color];
+ const lastIndex = colors.length - 1;
+ const assignCount = Math.min(lastIndex, uniqueValues.length);
+
+ // Assign first values one-to-one up to the penultimate color (if any)
+ for (let i = 0; i < assignCount; i++) {
+ // @ts-ignore tuple
+ colorMap[i][0] = uniqueValues[i];
+ }
+
+ if (uniqueValues.length > colors.length) {
+ // Aggregate the rest (including the value that would have gone to last color)
+ // Build aggregated array incrementally to match legacy behavior
+ const aggregatedValues: any[] = [];
+ for (let i = lastIndex; i < uniqueValues.length; i++) {
+ const value = uniqueValues[i];
+ if (Array.isArray(value)) {
+ // Spread array elements to match legacy flattening behavior
+ aggregatedValues.push(...(value as any[]));
+ } else {
+ aggregatedValues.push(value);
+ }
}
- return [null, color];
- });
+ // @ts-ignore tuple
+ colorMap[lastIndex][0] = aggregatedValues;
+ } else if (uniqueValues.length === colors.length) {
+ // Exactly one per color
+ // @ts-ignore tuple
+ colorMap[lastIndex][0] = uniqueValues[lastIndex];
+ }
+ // @ts-ignore tuple
return colorMap;
}
diff --git a/src/utils/src/data-utils.ts b/src/utils/src/data-utils.ts
index 7f7c7426e..93ff01ead 100644
--- a/src/utils/src/data-utils.ts
+++ b/src/utils/src/data-utils.ts
@@ -76,6 +76,7 @@ export function validateCoordinate(value: number, minValue: number, maxValue: nu
/**
* simple getting unique values of an array
+ * Note: filters out null and undefined values
*
* @param values
* @returns unique values
diff --git a/test/node/utils/data-scale-utils-test.js b/test/node/utils/data-scale-utils-test.js
index beb78112f..e1303f46c 100644
--- a/test/node/utils/data-scale-utils-test.js
+++ b/test/node/utils/data-scale-utils-test.js
@@ -15,7 +15,8 @@ import {
getDomainStepsbyZoom,
getQuantLabelFormat,
getHistogramDomain,
- getQuantLegends
+ getQuantLegends,
+ getCategoricalColorMap
} from '@kepler.gl/utils';
import {StateWFilesFiltersLayerColor} from 'test/helpers/mock-state';
import {SCALE_FUNC} from '@kepler.gl/constants';
@@ -251,3 +252,513 @@ test('DataScaleUtils -> getQuantLegends', t => {
);
t.end();
});
+
+test('DataScaleUtils -> getCategoricalColorMap -> basic functionality', t => {
+ // Test empty inputs
+ t.deepEqual(
+ getCategoricalColorMap([], []),
+ [],
+ 'should return empty array for empty colors and domain'
+ );
+
+ // Test empty colors with domain
+ t.deepEqual(
+ getCategoricalColorMap([], ['a', 'b']),
+ [],
+ 'should return empty array for empty colors'
+ );
+
+ // Test empty domain with colors
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], []),
+ [
+ [null, '#ff0000'],
+ [null, '#00ff00']
+ ],
+ 'should return colors with null values for empty domain'
+ );
+
+ // Test single color, single value
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000'], ['a']),
+ [['a', '#ff0000']],
+ 'should map single value to single color'
+ );
+
+ // Test single color, multiple values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000'], ['a', 'b', 'c']),
+ [[['a', 'b', 'c'], '#ff0000']],
+ 'should assign all values as array to single color when domain is larger'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> equal colors and domain', t => {
+ // Test equal number of colors and domain values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['a', 'b', 'c']),
+ [
+ ['a', '#ff0000'],
+ ['b', '#00ff00'],
+ ['c', '#0000ff']
+ ],
+ 'should map each value to corresponding color when counts are equal'
+ );
+
+ // Test with numbers
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [2, 1]),
+ [
+ [1, '#ff0000'],
+ [2, '#00ff00']
+ ],
+ 'should map sorted numeric values to colors'
+ );
+
+ // Test with mixed types (should be sorted)
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], [2, 'a', 1]),
+ [
+ [1, '#ff0000'],
+ [2, '#00ff00'],
+ ['a', '#0000ff']
+ ],
+ 'should sort mixed types and map to colors'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> more colors than domain', t => {
+ // Test more colors than domain values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['a', 'b']),
+ [
+ ['a', '#ff0000'],
+ ['b', '#00ff00'],
+ [null, '#0000ff']
+ ],
+ 'should assign values one-to-one and leave extra colors with null'
+ );
+
+ // Test with single domain value and multiple colors
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['z']),
+ [
+ ['z', '#ff0000'],
+ [null, '#00ff00'],
+ [null, '#0000ff']
+ ],
+ 'should assign single value to first color and leave others null'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> more domain than colors', t => {
+ // Test more domain values than colors
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['a', 'b', 'c', 'd']),
+ [
+ ['a', '#ff0000'],
+ [['b', 'c', 'd'], '#00ff00']
+ ],
+ 'should assign remaining values as array to last color'
+ );
+
+ // Test with many domain values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['a', 'b', 'c', 'd', 'e', 'f']),
+ [
+ ['a', '#ff0000'],
+ ['b', '#00ff00'],
+ [['c', 'd', 'e', 'f'], '#0000ff']
+ ],
+ 'should assign first values one-to-one up to penultimate color, then aggregate rest'
+ );
+
+ // Test with numeric values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [5, 1, 3, 2, 4]),
+ [
+ [1, '#ff0000'],
+ [[2, 3, 4, 5], '#00ff00']
+ ],
+ 'should sort numeric values and aggregate excess to last color'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> data types and null handling', t => {
+ // Test with null and undefined values in domain
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['a', null, 'b', undefined]),
+ [
+ ['a', '#ff0000'],
+ ['b', '#00ff00']
+ ],
+ 'should filter out null and undefined from domain'
+ );
+
+ // Test with only null/undefined in domain
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [null, undefined]),
+ [
+ [null, '#ff0000'],
+ [null, '#00ff00']
+ ],
+ 'should return colors with null values when domain only contains null/undefined'
+ );
+
+ // Test with zero value
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [0, 1, 2]),
+ [
+ [0, '#ff0000'],
+ [[1, 2], '#00ff00']
+ ],
+ 'should handle zero as valid value'
+ );
+
+ // Test with boolean values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [true, false]),
+ [
+ [false, '#ff0000'],
+ [true, '#00ff00']
+ ],
+ 'should handle boolean values and sort them correctly'
+ );
+
+ // Test with string numbers
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['1', '10', '2']),
+ [
+ ['1', '#ff0000'],
+ [['10', '2'], '#00ff00']
+ ],
+ 'should treat string numbers as strings and sort lexicographically'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> duplicate values', t => {
+ // Test with duplicate values in domain (should be deduplicated)
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['a', 'b', 'a', 'b', 'c']),
+ [
+ ['a', '#ff0000'],
+ [['b', 'c'], '#00ff00']
+ ],
+ 'should deduplicate domain values and sort them'
+ );
+
+ // Test with all duplicate values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['a', 'a', 'a']),
+ [
+ ['a', '#ff0000'],
+ [null, '#00ff00']
+ ],
+ 'should handle all duplicate values correctly'
+ );
+
+ // Test with numeric duplicates
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [1, 2, 1, 3, 2]),
+ [
+ [1, '#ff0000'],
+ [[2, 3], '#00ff00']
+ ],
+ 'should deduplicate and sort numeric values'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> sorting behavior', t => {
+ // Test string sorting
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['zebra', 'apple', 'banana']),
+ [
+ ['apple', '#ff0000'],
+ ['banana', '#00ff00'],
+ ['zebra', '#0000ff']
+ ],
+ 'should sort strings alphabetically'
+ );
+
+ // Test numeric sorting (JavaScript default sort converts to strings)
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], [10, 2, 1]),
+ [
+ [1, '#ff0000'],
+ [10, '#00ff00'],
+ [2, '#0000ff']
+ ],
+ 'should sort numbers lexicographically (as strings)'
+ );
+
+ // Test lexicographic sorting with multi-digit numbers
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [100, 20, 3]),
+ [
+ [100, '#ff0000'],
+ [[20, 3], '#00ff00']
+ ],
+ 'should sort multi-digit numbers lexicographically: 100 comes before 20'
+ );
+
+ // Test mixed string-number sorting (numbers come first when converted to strings)
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['b', 1, 'a', 2]),
+ [
+ [1, '#ff0000'],
+ [2, '#00ff00'],
+ [['a', 'b'], '#0000ff']
+ ],
+ 'should sort mixed types with numbers first'
+ );
+
+ // Test case sensitivity
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['B', 'a', 'A', 'b']),
+ [
+ ['A', '#ff0000'],
+ [['B', 'a', 'b'], '#00ff00']
+ ],
+ 'should be case sensitive in sorting'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> edge cases', t => {
+ // Test with empty string
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['', 'a', 'b']),
+ [
+ ['', '#ff0000'],
+ [['a', 'b'], '#00ff00']
+ ],
+ 'should handle empty string as valid value'
+ );
+
+ // Test with whitespace strings
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [' ', ' ', 'a']),
+ [
+ [' ', '#ff0000'],
+ [[' ', 'a'], '#00ff00']
+ ],
+ 'should handle whitespace strings as distinct values'
+ );
+
+ // Test with very long arrays
+ const longDomain = Array.from({length: 100}, (_, i) => `item${i}`);
+ const result = getCategoricalColorMap(['#ff0000', '#00ff00'], longDomain);
+ t.equal(result.length, 2, 'should handle large domain arrays');
+ t.equal(result[0][0], 'item0', 'should assign first value correctly for large arrays');
+ t.true(
+ Array.isArray(result[1][0]),
+ 'should aggregate remaining values into array for large domains'
+ );
+ t.equal(result[1][0].length, 99, 'should aggregate correct number of remaining values');
+
+ // Test with nested arrays/objects in domain (Set doesn't deduplicate by content)
+ const nestedArray = ['nested'];
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [nestedArray, 'string', nestedArray]),
+ [
+ [nestedArray, '#ff0000'],
+ ['string', '#00ff00']
+ ],
+ 'should handle complex types in domain (same reference gets deduplicated)'
+ );
+
+ // Test with different array instances (no deduplication)
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], [['nested'], 'string', ['nested']]),
+ [
+ [['nested'], '#ff0000'],
+ [['nested', 'string'], '#00ff00']
+ ],
+ 'should not deduplicate arrays with same content but different references'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> real-world scenarios', t => {
+ // Test typical categorical data (countries)
+ const countries = ['USA', 'Canada', 'Mexico', 'Brazil', 'Argentina'];
+ const countryColors = ['#ff0000', '#00ff00', '#0000ff'];
+ t.deepEqual(
+ getCategoricalColorMap(countryColors, countries),
+ [
+ ['Argentina', '#ff0000'],
+ ['Brazil', '#00ff00'],
+ [['Canada', 'Mexico', 'USA'], '#0000ff']
+ ],
+ 'should handle typical country categorical data'
+ );
+
+ // Test status/category data
+ const statuses = ['active', 'inactive', 'pending', 'archived'];
+ const statusColors = ['#28a745', '#dc3545', '#ffc107', '#6c757d'];
+ t.deepEqual(
+ getCategoricalColorMap(statusColors, statuses),
+ [
+ ['active', '#28a745'],
+ ['archived', '#dc3545'],
+ ['inactive', '#ffc107'],
+ ['pending', '#6c757d']
+ ],
+ 'should handle status/category data with exact color mapping'
+ );
+
+ // Test product categories
+ const categories = ['Electronics', 'Clothing', 'Books', 'Home & Garden', 'Sports'];
+ const categoryColors = ['#ff6b6b', '#4ecdc4'];
+ t.deepEqual(
+ getCategoricalColorMap(categoryColors, categories),
+ [
+ ['Books', '#ff6b6b'],
+ [['Clothing', 'Electronics', 'Home & Garden', 'Sports'], '#4ecdc4']
+ ],
+ 'should handle product categories with insufficient colors'
+ );
+
+ // Test age groups (numeric ranges as strings)
+ const ageGroups = ['18-25', '26-35', '36-45', '46-55', '55+'];
+ const ageColors = ['#e8f5e8', '#a8d8a8', '#68b968'];
+ t.deepEqual(
+ getCategoricalColorMap(ageColors, ageGroups),
+ [
+ ['18-25', '#e8f5e8'],
+ ['26-35', '#a8d8a8'],
+ [['36-45', '46-55', '55+'], '#68b968']
+ ],
+ 'should handle age group ranges correctly'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> color format variations', t => {
+ // Test with different color formats (hex colors)
+ t.deepEqual(
+ getCategoricalColorMap(['#FF0000', '#00FF00', '#0000FF'], ['a', 'b', 'c']),
+ [
+ ['a', '#FF0000'],
+ ['b', '#00FF00'],
+ ['c', '#0000FF']
+ ],
+ 'should handle uppercase hex colors'
+ );
+
+ // Test with short hex colors
+ t.deepEqual(
+ getCategoricalColorMap(['#f00', '#0f0', '#00f'], ['x', 'y', 'z']),
+ [
+ ['x', '#f00'],
+ ['y', '#0f0'],
+ ['z', '#00f']
+ ],
+ 'should handle short hex color format'
+ );
+
+ // Test with named colors (if the function accepts them)
+ t.deepEqual(
+ getCategoricalColorMap(['red', 'green', 'blue'], ['first', 'second', 'third']),
+ [
+ ['first', 'red'],
+ ['second', 'green'],
+ ['third', 'blue']
+ ],
+ 'should handle named color strings'
+ );
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> stress tests', t => {
+ // Test with single color and many domain values
+ const manyValues = Array.from({length: 50}, (_, i) => `value${i}`);
+ const singleColorResult = getCategoricalColorMap(['#ff0000'], manyValues);
+ t.equal(singleColorResult.length, 1, 'should return single color mapping for many values');
+ t.true(
+ Array.isArray(singleColorResult[0][0]),
+ 'should aggregate all values into array for single color'
+ );
+ t.equal(singleColorResult[0][0].length, 50, 'should contain all 50 values in the array');
+ t.equal(singleColorResult[0][0][0], 'value0', 'should have first sorted value at start of array');
+
+ // Test with many colors and single domain value
+ const manyColors = Array.from({length: 20}, (_, i) => `#${i.toString(16).padStart(6, '0')}`);
+ const singleValueResult = getCategoricalColorMap(manyColors, ['onlyValue']);
+ t.equal(singleValueResult.length, 20, 'should return all colors when only one domain value');
+ t.equal(singleValueResult[0][0], 'onlyValue', 'should assign value to first color');
+ for (let i = 1; i < 20; i++) {
+ t.equal(singleValueResult[i][0], null, `color ${i} should have null value`);
+ }
+
+ // Test performance with moderately large datasets
+ const largeDomain = Array.from({length: 1000}, (_, i) => `item${i}`);
+ const largeColors = Array.from({length: 10}, (_, i) => `#color${i}`);
+ const largeResult = getCategoricalColorMap(largeColors, largeDomain);
+ t.equal(largeResult.length, 10, 'should handle large datasets efficiently');
+ t.true(Array.isArray(largeResult[9][0]), 'should aggregate many values to last color');
+
+ t.end();
+});
+
+test('DataScaleUtils -> getCategoricalColorMap -> boundary conditions', t => {
+ // Test with exactly 2 colors and 2 values (boundary case)
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['b', 'a']),
+ [
+ ['a', '#ff0000'],
+ ['b', '#00ff00']
+ ],
+ 'should handle boundary case of 2 colors and 2 values'
+ );
+
+ // Test with exactly 3 colors and 3 values
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['z', 'a', 'm']),
+ [
+ ['a', '#ff0000'],
+ ['m', '#00ff00'],
+ ['z', '#0000ff']
+ ],
+ 'should handle boundary case of 3 colors and 3 values'
+ );
+
+ // Test transitioning from equal to more domains than colors
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00'], ['a', 'b', 'c']),
+ [
+ ['a', '#ff0000'],
+ [['b', 'c'], '#00ff00']
+ ],
+ 'should transition correctly from equal to excess domain values'
+ );
+
+ // Test transitioning from more colors to equal
+ t.deepEqual(
+ getCategoricalColorMap(['#ff0000', '#00ff00', '#0000ff'], ['b', 'a']),
+ [
+ ['a', '#ff0000'],
+ ['b', '#00ff00'],
+ [null, '#0000ff']
+ ],
+ 'should transition correctly from excess colors to matching'
+ );
+
+ t.end();
+});