UNPKG

@dr.pogodin/react-global-state

Version:
72 lines (68 loc) 2.44 kB
import { cloneDeep } from 'lodash-es'; // TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils // lib. /** * Given the type of state, `StateT`, and the type of state path, `PathT`, * it evaluates the type of value at that path of the state, if it can be * evaluated from the path type (it is possible when `PathT` is a string * literal type, and `StateT` elements along this path have appropriate * types); otherwise it falls back to the specified `UnknownT` type, * which should be set either `never` (for input arguments), or `void` * (for return types) - `never` and `void` in those places forbid assignments, * and are not auto-inferred to more permissible types. * * BEWARE: When StateT is any the construct resolves to any for any string * paths. */ /** * Returns 'true' if debug logging should be performed; 'false' otherwise. * * BEWARE: The actual safeguards for the debug logging still should read * if (process.env.NODE_ENV !== 'production' && isDebugMode()) { * // Some debug logging * } * to ensure that debug code is stripped out by Webpack in production mode. * * @returns * @ignore */ export function isDebugMode() { try { return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG; } catch { return false; } } const cloneDeepBailKeys = new Set(); /** * Deep-clones given value for logging purposes, or returns the value itself * if the previous clone attempt, with the same key, took more than 300ms * (to avoid situations when large payload in the global state slows down * development versions of the app due to the logging overhead). */ export function cloneDeepForLog(value, key = '') { if (cloneDeepBailKeys.has(key)) { // eslint-disable-next-line no-console console.warn(`The logged value won't be clonned (key "${key}").`); return value; } const start = Date.now(); const res = cloneDeep(value); const time = Date.now() - start; if (time > 300) { // eslint-disable-next-line no-console console.warn(`${time}ms spent to clone the logged value (key "${key}").`); cloneDeepBailKeys.add(key); } return res; } export function areEqual(a, b) { for (const [key, value] of Object.entries(a)) { if (b[key] !== value) return false; } for (const [key, value] of Object.entries(b)) { if (a[key] !== value) return false; } return true; } //# sourceMappingURL=utils.js.map