diff --git a/src/reducers/subnetwork.js b/src/reducers/subnetwork.js index abfd075..e0b51d6 100644 --- a/src/reducers/subnetwork.js +++ b/src/reducers/subnetwork.js @@ -5,36 +5,7 @@ import { REMOVE_SUPER_NODE, } from 'actions'; -const colorsBuilder = () => { - let list = []; - const allColors = ['#D84315', '#BF360C', '#FBC02D', '#F9A825', '#F57F17', '#FFA000', '#FF8F00', '#FF6F00', '#F57C00', '#EF6C00', '#E65100', '#388E3C', '#2E7D32', '#689F38', '#558B2F', '#AFB42B', '#0288D1', '#0097A7', '#00838F', '#1976D2', '#1565C0', '#C2185B']; - const shuffle = (array) => { - let currentIndex = array.length; - let temporaryValue; - let randomIndex; - - while (currentIndex !== 0) { - randomIndex = Math.floor(Math.random() * currentIndex); - currentIndex -= 1; - - temporaryValue = array[currentIndex]; - array[currentIndex] = array[randomIndex]; - array[randomIndex] = temporaryValue; - } - - return array; - }; - - return () => { - if (list.length === 0) { - list = shuffle([...allColors]); - } - - return list.shift(); - }; -}; - -const colorsNol = colorsBuilder(); +import { getRandomColor } from 'utils/colors'; const formatNetwork = (state) => { const { network, positions, nodes } = state; @@ -44,7 +15,7 @@ const formatNetwork = (state) => { ...network, nodes, positions, - color: colorsNol(), + color: getRandomColor(), }; } diff --git a/src/utils/colors.js b/src/utils/colors.js new file mode 100644 index 0000000..eb6a35a --- /dev/null +++ b/src/utils/colors.js @@ -0,0 +1,40 @@ +import { sort, isEmpty } from 'ramda'; + +export const COLORS = [ + '#D84315', + '#BF360C', + '#FBC02D', + '#F9A825', + '#F57F17', + '#FFA000', + '#FF8F00', + '#FF6F00', + '#F57C00', + '#EF6C00', + '#E65100', + '#388E3C', + '#2E7D32', + '#689F38', + '#558B2F', + '#AFB42B', + '#0288D1', + '#0097A7', + '#00838F', + '#1976D2', + '#1565C0', + '#C2185B', +]; + +const shuffle = sort(() => Math.random() - 0.5); + +const createRandomColorBuilder = () => { + let list = []; + return () => { + if (isEmpty(list)) { + list = shuffle(COLORS); + } + return list.shift(); + }; +}; + +export const getRandomColor = createRandomColorBuilder(); diff --git a/src/utils/colors.test.js b/src/utils/colors.test.js new file mode 100644 index 0000000..3572d2c --- /dev/null +++ b/src/utils/colors.test.js @@ -0,0 +1,27 @@ +import { times } from 'ramda'; +import { COLORS, getRandomColor } from './colors'; + +describe('Colors Utils', () => { + describe('getRandomColor', () => { + beforeAll(() => { + jest.spyOn(Math, 'random').mockReturnValue(0.5); + }); + + afterAll(() => { + Math.random.mockRestore(); + }); + + it('returns "#388E3C" on the first time', () => { + expect(getRandomColor()).toBe('#388E3C'); + }); + + it('returns "#D84315" on the second time', () => { + expect(getRandomColor()).toBe('#D84315'); + }); + + it('returns "#388E3C" on the twenty first time', () => { + times(getRandomColor, COLORS.length - 2); + expect(getRandomColor()).toBe('#388E3C'); + }); + }); +});