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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import type { PayloadAction } from '@reduxjs/toolkit'
import { combineReducers, configureStore, createSlice } from '@reduxjs/toolkit'
import { test } from 'vitest'
import type { AnyFunction, OutputSelector, Simplify } from '../src/types'

export interface Todo {
  id: number
  title: string
  description: string
  completed: boolean
}

interface Alert {
  id: number
  message: string
  type: string
  read: boolean
}

interface BillingAddress {
  street: string
  city: string
  state: string
  zip: string
}

interface Address extends BillingAddress {
  billing: BillingAddress
}

interface PushNotification {
  enabled: boolean
  frequency: string
}

interface Notifications {
  email: boolean
  sms: boolean
  push: PushNotification
}

interface Preferences {
  newsletter: boolean
  notifications: Notifications
}

interface Login {
  lastLogin: string
  loginCount: number
}

interface UserDetails {
  name: string
  email: string
  address: Address
  preferences: Preferences
}

interface User {
  id: number
  details: UserDetails
  status: string
  login: Login
}

interface AppSettings {
  theme: string
  language: string
}

interface UserState {
  user: User
  appSettings: AppSettings
}

let nextTodoId = 0

// For long arrays
const todoState = [
  {
    id: nextTodoId++,
    title: 'Buy groceries',
    description: 'Milk, bread, eggs, and fruits',
    completed: false
  },
  {
    id: nextTodoId++,
    title: 'Schedule dentist appointment',
    description: 'Check available slots for next week',
    completed: false
  },
  {
    id: nextTodoId++,
    title: 'Convince the cat to get a job',
    description: 'Need extra income for cat treats',
    completed: false
  },
  {
    id: nextTodoId++,
    title: 'Figure out if plants are plotting world domination',
    description: 'That cactus looks suspicious...',
    completed: false
  },
  {
    id: nextTodoId++,
    title: 'Practice telekinesis',
    description: 'Try moving the remote without getting up',
    completed: false
  },
  {
    id: nextTodoId++,
    title: 'Determine location of El Dorado',
    description: 'Might need it for the next vacation',
    completed: false
  },
  {
    id: nextTodoId++,
    title: 'Master the art of invisible potato juggling',
    description: 'Great party trick',
    completed: false
  }
]

export const createTodoItem = () => {
  const id = nextTodoId++
  return {
    id,
    title: `Task ${id}`,
    description: `Description for task ${id}`,
    completed: false
  }
}

export const pushToTodos = (limit: number) => {
  const { length: todoStateLength } = todoState
  // const limit = howMany + todoStateLength
  for (let i = todoStateLength; i < limit; i++) {
    todoState.push(createTodoItem())
  }
}

pushToTodos(200)

const alertState = [
  {
    id: 0,
    message: 'You have an upcoming meeting at 3 PM.',
    type: 'reminder',
    read: false
  },
  {
    id: 1,
    message: 'New software update available.',
    type: 'notification',
    read: false
  },
  {
    id: 3,
    message:
      'The plants have been watered, but keep an eye on that shifty cactus.',
    type: 'notification',
    read: false
  },
  {
    id: 4,
    message:
      'Telekinesis class has been moved to 5 PM. Please do not bring any spoons.',
    type: 'reminder',
    read: false
  },
  {
    id: 5,
    message:
      'Expedition to El Dorado is postponed. The treasure map is being updated.',
    type: 'notification',
    read: false
  },
  {
    id: 6,
    message:
      'Invisible potato juggling championship is tonight. May the best mime win.',
    type: 'reminder',
    read: false
  }
]

// For nested fields tests
const userState: UserState = {
  user: {
    id: 0,
    details: {
      name: 'John Doe',
      email: 'john.doe@example.com',
      address: {
        street: '123 Main St',
        city: 'AnyTown',
        state: 'CA',
        zip: '12345',
        billing: {
          street: '456 Main St',
          city: 'AnyTown',
          state: 'CA',
          zip: '12345'
        }
      },
      preferences: {
        newsletter: true,
        notifications: {
          email: true,
          sms: false,
          push: {
            enabled: true,
            frequency: 'daily'
          }
        }
      }
    },
    status: 'active',
    login: {
      lastLogin: '2023-04-30T12:34:56Z',
      loginCount: 123
    }
  },
  appSettings: {
    theme: 'dark',
    language: 'en-US'
  }
}

const todoSlice = createSlice({
  name: 'todos',
  initialState: todoState,
  reducers: {
    toggleCompleted: (state, action: PayloadAction<number>) => {
      const todo = state.find(todo => todo.id === action.payload)
      if (todo) {
        todo.completed = !todo.completed
      }
    },

    addTodo: (state, action: PayloadAction<Omit<Todo, 'id' | 'completed'>>) => {
      // const newId = state.length > 0 ? state[state.length - 1].id + 1 : 0
      const newId = nextTodoId++
      state.push({
        ...action.payload,
        id: newId,
        completed: false
      })
    },

    removeTodo: (state, action: PayloadAction<number>) => {
      return state.filter(todo => todo.id !== action.payload)
    },

    updateTodo: (state, action: PayloadAction<Todo>) => {
      const index = state.findIndex(todo => todo.id === action.payload.id)
      if (index !== -1) {
        state[index] = action.payload
      }
    },

    clearCompleted: state => {
      return state.filter(todo => !todo.completed)
    }
  }
})

const alertSlice = createSlice({
  name: 'alerts',
  initialState: alertState,
  reducers: {
    markAsRead: (state, action: PayloadAction<number>) => {
      const alert = state.find(alert => alert.id === action.payload)
      if (alert) {
        alert.read = true
      }
    },

    toggleRead: (state, action: PayloadAction<number>) => {
      const alert = state.find(alert => alert.id === action.payload)
      if (alert) {
        alert.read = !alert.read
      }
    },

    addAlert: (state, action: PayloadAction<Omit<Alert, 'id'>>) => {
      const newId = state.length > 0 ? state[state.length - 1].id + 1 : 0
      state.push({
        ...action.payload,
        id: newId
      })
    },

    removeAlert: (state, action: PayloadAction<number>) => {
      return state.filter(alert => alert.id !== action.payload)
    }
  }
})

const userSlice = createSlice({
  name: 'users',
  initialState: userState,
  reducers: {
    setUserName: (state, action: PayloadAction<string>) => {
      state.user.details.name = action.payload
    },

    setUserEmail: (state, action: PayloadAction<string>) => {
      state.user.details.email = action.payload
    },

    setAppTheme: (state, action: PayloadAction<string>) => {
      state.appSettings.theme = action.payload
    },

    updateUserStatus: (state, action: PayloadAction<string>) => {
      state.user.status = action.payload
    },

    updateLoginDetails: (
      state,
      action: PayloadAction<{ lastLogin: string; loginCount: number }>
    ) => {
      state.user.login = { ...state.user.login, ...action.payload }
    },

    updateUserAddress: (state, action: PayloadAction<Address>) => {
      state.user.details.address = {
        ...state.user.details.address,
        ...action.payload
      }
    },

    updateBillingAddress: (state, action: PayloadAction<BillingAddress>) => {
      state.user.details.address.billing = {
        ...state.user.details.address.billing,
        ...action.payload
      }
    },

    toggleNewsletterSubscription: state => {
      state.user.details.preferences.newsletter =
        !state.user.details.preferences.newsletter
    },

    setNotificationPreferences: (
      state,
      action: PayloadAction<Notifications>
    ) => {
      state.user.details.preferences.notifications = {
        ...state.user.details.preferences.notifications,
        ...action.payload
      }
    },

    updateAppLanguage: (state, action: PayloadAction<string>) => {
      state.appSettings.language = action.payload
    }
  }
})

const rootReducer = combineReducers({
  [todoSlice.name]: todoSlice.reducer,
  [alertSlice.name]: alertSlice.reducer,
  [userSlice.name]: userSlice.reducer
})

export const setupStore = (preloadedState?: Partial<RootState>) => {
  return configureStore({ reducer: rootReducer, preloadedState })
}

export type AppStore = Simplify<ReturnType<typeof setupStore>>

export type RootState = ReturnType<typeof rootReducer>

export interface LocalTestContext {
  store: AppStore
  state: RootState
}

export const { markAsRead, addAlert, removeAlert, toggleRead } =
  alertSlice.actions

export const {
  toggleCompleted,
  addTodo,
  removeTodo,
  updateTodo,
  clearCompleted
} = todoSlice.actions

export const { setUserName, setUserEmail, setAppTheme } = userSlice.actions

// Since Node 16 does not support `structuredClone`
export const deepClone = <T extends object>(object: T): T =>
  JSON.parse(JSON.stringify(object))

export const setFunctionName = (func: AnyFunction, name: string) => {
  Object.defineProperty(func, 'name', { value: name })
}

export const setFunctionNames = (funcObject: Record<string, AnyFunction>) => {
  Object.entries(funcObject).forEach(([key, value]) =>
    setFunctionName(value, key)
  )
}

const store = setupStore()
const state = store.getState()

export const localTest = test.extend<LocalTestContext>({
  store,
  state
})

export const resetSelector = <S extends OutputSelector>(selector: S) => {
  selector.clearCache()
  selector.resetRecomputations()
  selector.resetDependencyRecomputations()
  selector.memoizedResultFunc.clearCache()
}

export const logRecomputations = <S extends OutputSelector>(selector: S) => {
  console.log(
    `${selector.name} result function recalculated:`,
    selector.recomputations(),
    `time(s)`,
    `input selectors recalculated:`,
    selector.dependencyRecomputations(),
    `time(s)`
  )
}

export const logSelectorRecomputations = <S extends OutputSelector>(
  selector: S
) => {
  console.log(`\x1B[32m\x1B[1m${selector.name}\x1B[0m:`, {
    resultFunc: selector.recomputations(),
    inputSelectors: selector.dependencyRecomputations(),
    newResults:
      typeof selector.memoizedResultFunc.resultsCount === 'function'
        ? selector.memoizedResultFunc.resultsCount()
        : undefined
  })
  // console.log(
  //   `\x1B[32m\x1B[1m${selector.name}\x1B[0m result function recalculated:`,
  //   `\x1B[33m${selector.recomputations().toLocaleString('en-US')}\x1B[0m`,
  //   'time(s)',
  //   `input selectors recalculated:`,
  //   `\x1B[33m${selector
  //     .dependencyRecomputations()
  //     .toLocaleString('en-US')}\x1B[0m`,
  //   'time(s)'
  // )
}

export const logFunctionInfo = (func: AnyFunction, recomputations: number) => {
  console.log(
    `\x1B[32m\x1B[1m${func.name}\x1B[0m was called:`,
    recomputations,
    'time(s)'
  )
}

export const safeApply = <Params extends any[], Result>(
  func: (...args: Params) => Result,
  args: Params
) => func.apply<null, Params, Result>(null, args)

export const countRecomputations = <
  Params extends any[],
  Result,
  AdditionalFields
>(
  func: ((...args: Params) => Result) & AdditionalFields
) => {
  let recomputations = 0
  const wrapper = (...args: Params) => {
    recomputations++
    return safeApply(func, args)
  }
  return Object.assign(
    wrapper,
    {
      recomputations: () => recomputations,
      resetRecomputations: () => (recomputations = 0)
    },
    func
  )
}

export const runMultipleTimes = <Params extends any[]>(
  func: (...args: Params) => any,
  times: number,
  ...args: Params
) => {
  for (let i = 0; i < times; i++) {
    safeApply(func, args)
  }
}

export const expensiveComputation = (times = 1_000_000) => {
  for (let i = 0; i < times; i++) {
    // Do nothing
  }
}

export const setEnvToProd = () => {
  vi.stubEnv('NODE_ENV', 'production')
  return vi.unstubAllEnvs
}

export const isMemoizedSelector = (selector: object) => {
  return (
    typeof selector === 'function' &&
    'resultFunc' in selector &&
    'memoizedResultFunc' in selector &&
    'lastResult' in selector &&
    'dependencies' in selector &&
    'recomputations' in selector &&
    'dependencyRecomputations' in selector &&
    'resetRecomputations' in selector &&
    'resetDependencyRecomputations' in selector &&
    'memoize' in selector &&
    'argsMemoize' in selector &&
    typeof selector.resultFunc === 'function' &&
    typeof selector.memoizedResultFunc === 'function' &&
    typeof selector.lastResult === 'function' &&
    Array.isArray(selector.dependencies) &&
    typeof selector.recomputations === 'function' &&
    typeof selector.dependencyRecomputations === 'function' &&
    typeof selector.resetRecomputations === 'function' &&
    typeof selector.resetDependencyRecomputations === 'function' &&
    typeof selector.memoize === 'function' &&
    typeof selector.argsMemoize === 'function' &&
    selector.dependencies.length >= 1 &&
    selector.dependencies.every(
      (dependency): dependency is Function => typeof dependency === 'function'
    ) &&
    !selector.lastResult.length &&
    !selector.recomputations.length &&
    !selector.resetRecomputations.length &&
    typeof selector.recomputations() === 'number' &&
    typeof selector.dependencyRecomputations() === 'number'
  )
}