|
| 1 | +import { createSlice } from '@reduxjs/toolkit' |
| 2 | +import * as c from './constants' |
| 3 | + |
| 4 | +import { TEXT_INPUT_MOD, TREE_DEPTH } from './constants' |
| 5 | + |
| 6 | +const { reducer, actions } = createSlice({ |
| 7 | + name: 'strings', |
| 8 | + initialState: {}, |
| 9 | + reducers: { |
| 10 | + initialize(state, action) { |
| 11 | + const { stringId } = action.payload |
| 12 | + state[stringId] = 'a' |
| 13 | + }, |
| 14 | + append(state, action) { |
| 15 | + const { stringId, character } = action.payload |
| 16 | + |
| 17 | + if (state[stringId]) { |
| 18 | + state[stringId] += character |
| 19 | + } |
| 20 | + //const value = state[counterId] || 0; |
| 21 | + //state[counterId] = value + 1; |
| 22 | + }, |
| 23 | + appendMany(state, action) { |
| 24 | + const { mod, character } = action.payload |
| 25 | + const keys = Object.keys(state) |
| 26 | + |
| 27 | + keys.forEach((stringId, index) => { |
| 28 | + if (index % mod === 0) { |
| 29 | + state[stringId] += character |
| 30 | + } |
| 31 | + }) |
| 32 | + for (let counterId = 0; counterId < c.NUMBER_OF_SLICES; counterId++) { |
| 33 | + if (counterId % mod === 0) { |
| 34 | + const value = state[counterId] || 0 |
| 35 | + state[counterId] = value + 1 |
| 36 | + } |
| 37 | + } |
| 38 | + }, |
| 39 | + }, |
| 40 | +}) |
| 41 | + |
| 42 | +export const { initialize, append, appendMany } = actions |
| 43 | + |
| 44 | +const CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 45 | +let nextCharCounter = 0 |
| 46 | + |
| 47 | +export function createStringId(sliceId, depth) { |
| 48 | + const stringId = `${sliceId}-${depth}` |
| 49 | + return stringId |
| 50 | +} |
| 51 | + |
| 52 | +function getNextCharacter() { |
| 53 | + const charIndex = nextCharCounter % CHARACTERS.length |
| 54 | + nextCharCounter++ |
| 55 | + const character = CHARACTERS.charAt(charIndex) |
| 56 | + return character |
| 57 | +} |
| 58 | + |
| 59 | +function getRandomInt(min, max) { |
| 60 | + min = Math.ceil(min) |
| 61 | + max = Math.floor(max) |
| 62 | + return Math.floor(Math.random() * (max - min + 1)) + min |
| 63 | +} |
| 64 | + |
| 65 | +export function appendRandomCharacter() { |
| 66 | + const sliceId = getRandomInt(0, c.NUMBER_OF_SLICES) |
| 67 | + const maxTextsPerSlice = Math.floor(TREE_DEPTH / TEXT_INPUT_MOD) |
| 68 | + const selectedTextId = getRandomInt(1, maxTextsPerSlice) |
| 69 | + |
| 70 | + const character = getNextCharacter() |
| 71 | + |
| 72 | + const stringId = createStringId(sliceId, selectedTextId) |
| 73 | + |
| 74 | + return append({ stringId, character }) |
| 75 | +} |
| 76 | + |
| 77 | +export function appendRandomCharToMany(mod) { |
| 78 | + const character = getNextCharacter() |
| 79 | + |
| 80 | + return appendMany({ mod, character }) |
| 81 | +} |
| 82 | + |
| 83 | +export default reducer |
0 commit comments