Skip to content

Commit

Permalink
Add hash coloring functions for d3 charts; call when value is string (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
cmatzenbach authored Aug 5, 2024
1 parent da19d68 commit e9efd18
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion src/mixins/color-mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,11 @@ export default function colorMixin(_chart) {
const range = _chart.colors().range()
const middleColor = range[Math.floor(range.length / 2)]

return _colors(_colorAccessor.call(this, data, index)) || middleColor
const value = _colorAccessor.call(this, data, index)

return typeof value === "string"
? _chart.determineColorByValue(value, range)
: _colors(_colorAccessor.call(this, data, index)) || middleColor
}

/**
Expand All @@ -185,5 +189,35 @@ export default function colorMixin(_chart) {
return _chart
}

const cyrb53 = (str, seed = 0) => {
let h1 = 0xdeadbeef ^ seed
let h2 = 0x41c6ce57 ^ seed
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i)
h1 = Math.imul(h1 ^ ch, 2654435761)
h2 = Math.imul(h2 ^ ch, 1597334677)
}

h1 =
Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^
Math.imul(h2 ^ (h2 >>> 13), 3266489909)

h2 =
Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^
Math.imul(h1 ^ (h1 >>> 13), 3266489909)

return 4294967296 * (2097151 & h2) + (h1 >>> 0)
}

_chart.determineColorByValue = (measureColor, colors) => {
if (typeof measureColor === "string") {
const hash = cyrb53(measureColor)
const colorIndex = hash % colors.length
return colors[colorIndex]
}
const colorIndex = measureColor % colors.length
return colors[colorIndex]
}

return _chart
}

0 comments on commit e9efd18

Please sign in to comment.