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