import { Color } from '@thematic/color' ; import murmur from 'murmurhash-js' ; import { linear , log , quantile } from '../scales' ; import { ScaleType , NominalColorScaleFunction , ContinuousColorScaleFunction , } from '../types' ; param colors param domain export function nominal ( colors , /**
 * Optionally pass in a list of values to pre-seed the color assignment.
 * They'll be sorted (natural) so other theme instances behave the same.
 */ domain ? ) { const colorCache = new Map ( ) ; if ( domain ) { const sorted = [ ... domain ] . sort ( ) ; sorted . forEach ( ( key , idx ) => { colorCache . set ( `${ key }` , colors [ idx ] ) ; } ) ; } const getColor = ( key ) => { const strkey = `${ key }` ; if ( ! colorCache . has ( strkey ) ) { const hash = typeof key === 'number' ? key : murmur . murmur3 ( strkey , 0xabcdef ) ; colorCache . set ( strkey , colors [ hash % colors . length ] ) ; } const cached = colorCache . get ( strkey ) ; return cached || 'none' ; } ; const fn = ( key ) => { const color = getColor ( key ) ; return new Color ( color ) ; } ; fn . toArray = function ( length ? ) { const l = length ? length : domain ? domain . length : colors . length ; return new Array ( l ) . fill ( 1 ) . map ( ( a , i ) => { return fn ( i ) . hex ( ) ; } ) ; } ; return fn ; } export function continuous ( colorStops , domain , scaleType , quantiles ? ) { let scale ; const safedomain = domain . map ( d => ( d === 0 ? 1e-10 : d ) ) ; switch ( scaleType ) { case ScaleType . Log : scale = log ( safedomain ) ; break ; case ScaleType . Quantile : scale = quantile ( domain , quantiles || 10 ) ; break ; default : scale = linear ( domain ) ; break ; } const { length } = colorStops ; const max = length - 1 ; const fn = ( value ) => { const index = Math . floor ( scale ( value ) * max ) ; const i = index < 0 ? 0 : index > max ? max : index ; const color = colorStops [ i ] ; return new Color ( color ) ; } ; fn . toArray = function ( length ? ) { const l = length || colorStops . length ; const step = ( domain [ domain . length - 1 ] - domain [ 0 ] ) / l ; return new Array ( l ) . fill ( 1 ) . map ( ( a , i ) => { return fn ( step * i ) . hex ( ) ; } ) ; } ; return fn ; }