Skip to content

Instantly share code, notes, and snippets.

View exuanbo's full-sized avatar
🎯
Focusing

Xuanbo Cheng exuanbo

🎯
Focusing
View GitHub Profile
{
// Text Editor
"editor.bracketPairColorization.enabled": false,
"editor.guides.bracketPairs": "active",
"editor.rulers": [100],
"editor.semanticHighlighting.enabled": true,
"editor.stickyScroll.enabled": true,
// Text Editor -> Cursor
"editor.cursorBlinking": "smooth",
const stringToColor = (str: string) => {
let hash = 0
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash)
}
let color = '#'
for (let i = 0; i < 3; i++) {
const value = (hash >> (i * 8)) & 0xff
color += `00${value.toString(16)}`.slice(-2)
}
interface StateRefObject<T> {
readonly current: T
}
export const useStateWithRef = <T>(
initialValue: T | (() => T)
): [T, React.Dispatch<React.SetStateAction<T>>, StateRefObject<T>] => {
const [state, __setState] = useState(initialValue)
const stateRef = useRef(state)
export const tap =
<T>(fn: (arg: T) => void) =>
(arg: T): T => {
fn(arg)
return arg
}
export const unary =
<T, R>(fn: (arg1: T, ...args: unknown[]) => R) =>
(arg1: T): R =>
fn(arg1)
export const range = (n: number): number[] => Array.from({ length: n }, (_, i) => i)
// https://stackoverflow.com/a/63790089/13346012
export type Head<T extends unknown[]> = T extends [...infer Head, unknown] ? Head : unknown[]
type PartiallyRequired<T, K extends keyof T> = Omit<T, K> & Pick<Required<T>, K>
export const isModuleAvailable = (path: string): boolean => {
try {
require.resolve(path)
return true
} catch {
return false
}
}
export const unwrap = <T>(
value: T | undefined | null,
errorMessage?: string
): T | never => {
if (value === null || value === undefined) {
throw new Error(errorMessage ?? 'Missing value')
}
return value
}