mirror of
https://github.com/Sped0n/bridget.git
synced 2026-04-14 10:09:31 -07:00
refactor(state.ts): improve code readability by adding comments and organizing code into sections
feat(state.ts): add nextFive property to state object to store the next five indices for preload feat(state.ts): add getNextFive function to calculate the next five indices based on the current index and length
This commit is contained in:
@@ -1,6 +1,16 @@
|
||||
import { updateIndexText, updateThresholdText } from './nav'
|
||||
import { Watchable, decrement, increment } from './utils'
|
||||
|
||||
/**
|
||||
* types
|
||||
*/
|
||||
|
||||
export type State = typeof defaultState
|
||||
|
||||
/**
|
||||
* variables
|
||||
*/
|
||||
|
||||
const thresholds = [
|
||||
{ threshold: 20, trailLength: 20 },
|
||||
{ threshold: 40, trailLength: 10 },
|
||||
@@ -11,18 +21,22 @@ const thresholds = [
|
||||
|
||||
const defaultState = {
|
||||
index: -1,
|
||||
nextFive: new Array(), // for preload
|
||||
length: 0,
|
||||
threshold: thresholds[2].threshold,
|
||||
trailLength: thresholds[2].trailLength
|
||||
}
|
||||
|
||||
export type State = typeof defaultState
|
||||
|
||||
export const state = new Watchable<State>(defaultState)
|
||||
|
||||
/**
|
||||
* main functions
|
||||
*/
|
||||
|
||||
export function initState(length: number): void {
|
||||
const s = state.get()
|
||||
s.length = length
|
||||
s.nextFive = getNextFive(s.index, s.length)
|
||||
state.set(s)
|
||||
state.addWatcher(() => {
|
||||
updateIndexText()
|
||||
@@ -33,18 +47,21 @@ export function initState(length: number): void {
|
||||
export function setIndex(index: number): void {
|
||||
const s = state.get()
|
||||
s.index = index
|
||||
s.nextFive = getNextFive(s.index, s.length)
|
||||
state.set(s)
|
||||
}
|
||||
|
||||
export function incIndex(): void {
|
||||
const s = state.get()
|
||||
s.index = increment(s.index, s.length)
|
||||
s.nextFive = getNextFive(s.index, s.length)
|
||||
state.set(s)
|
||||
}
|
||||
|
||||
export function decIndex(): void {
|
||||
const s = state.get()
|
||||
s.index = decrement(s.index, s.length)
|
||||
s.nextFive = getNextFive(s.index, s.length)
|
||||
state.set(s)
|
||||
}
|
||||
|
||||
@@ -60,7 +77,9 @@ export function decThreshold(): void {
|
||||
state.set(s)
|
||||
}
|
||||
|
||||
// helper
|
||||
/**
|
||||
* helper
|
||||
*/
|
||||
|
||||
function updateThreshold(state: State, inc: number): State {
|
||||
const i = thresholds.findIndex((t) => state.threshold === t.threshold)
|
||||
@@ -69,3 +88,11 @@ function updateThreshold(state: State, inc: number): State {
|
||||
if (!newItems) return state
|
||||
return { ...state, ...newItems }
|
||||
}
|
||||
|
||||
export function getNextFive(index: number, length: number): number[] {
|
||||
const five = []
|
||||
for (let i = 0; i < 5; i++) {
|
||||
five.push(increment(index + i, length))
|
||||
}
|
||||
return five
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user