Simplified ColorGenerator and exposed method to set colors for a key

This commit is contained in:
Alejandro Celaya 2018-08-18 17:51:44 +02:00
parent 2650027c40
commit 878e336ba1

View file

@ -1,37 +1,46 @@
import Storage from './Storage'; import Storage from './Storage';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { range } from 'ramda';
const buildRandomColor = () => { const { floor, random } = Math;
const letters = '0123456789ABCDEF'; const letters = '0123456789ABCDEF';
let color = '#'; const buildRandomColor = () =>
for (let i = 0; i < 6; i++ ) { `#${
color += letters[Math.floor(Math.random() * 16)]; range(0, 6)
} .map(() => letters[floor(random() * 16)])
return color; .join('')
}; }`;
export class ColorGenerator { export class ColorGenerator {
constructor(storage) { constructor(storage) {
this.storage = storage; this.storage = storage;
this.colors = this.storage.get('colors') || {}; this.colors = this.storage.get('colors') || {};
this.getColorForKey = this.getColorForKey.bind(this);
this.setColorForKey = this.setColorForKey.bind(this);
} }
getColorForKey = key => { getColorForKey = key => {
let color = this.colors[key]; const color = this.colors[key];
if (color) {
return color;
}
// If a color has not been set yet, generate a random one and save it // If a color has not been set yet, generate a random one and save it
color = buildRandomColor(); if (!color) {
this.colors[key] = color; this.setColorForKey(key, buildRandomColor());
this.storage.set('colors', this.colors); return this.getColorForKey(key);
}
return color; return color;
}; };
setColorForKey = (key, color) => {
this.colors[key] = color;
this.storage.set('colors', this.colors);
}
} }
export const colorGeneratorType = PropTypes.shape({ export const colorGeneratorType = PropTypes.shape({
getColorForKey: PropTypes.func, getColorForKey: PropTypes.func,
setColorForKey: PropTypes.func,
}); });
export default new ColorGenerator(Storage); export default new ColorGenerator(Storage);