Skip to content

Instantly share code, notes, and snippets.

@codenickycode
codenickycode / pojoEnum.ts
Last active December 30, 2022 21:26
[TS: enum -> pojo] Use a pojo instead of an enum #typescript #enum
const SomeEnum = {
SomeValue: 'SomeValue',
SomeOtherValue: 'SomeOtherValue'
} as const;
type SomeEnumKey = keyof typeof SomeEnum
@codenickycode
codenickycode / useContext.tsx
Created December 30, 2022 21:12
[React: Context Boilerplate] Sets up a hook to use context without the undefined initialization value #react #context
type FooContextType = { some: 'type' };
export const FooContext = React.createContext<FooContextType | undefined>(
undefined
);
export function FooProvider(props: { children: React.ReactNode }): JSX.Element {
const value = useFoo();
return (
<FooContext.Provider value={value}>{props.children}</FooContext.Provider>
@codenickycode
codenickycode / sdkProxy.ts
Created December 30, 2022 21:03
[TS: SDK Proxy] Wrap a script-added SDK so it is usable in server and client contexts #typescript #browser #sdk #script
declare global {
interface Window {
someSDK: SomeSDKType | undefined;
}
}
/**
* Wrap a script-added SDK so it is usable in server and client contexts.
* This allows it to be freely used without errors related to undefined `window`
*/
@codenickycode
codenickycode / browserOnly.ts
Last active December 30, 2022 21:12
[TS: Browser Only Function] Executes fn arg only if window is in global #typescript #browser
/**
* Safely execute browser only code.
*
* @param fn - The function to execute.
* @param fallback - Optional default return value.
*
*/
function browserOnly<T>(
fn: (window: Window, document: Document) => T,
fallback?: T
@codenickycode
codenickycode / reverse-percentages.txt
Last active December 30, 2022 17:31
[Reverse Percentages] Reverse calculate original amount given a percentage #math
1. Add or subtract the percentage given in the problem from 100% to determine what percentage we have.
2. Find 1% by dividing by the percentage found in the previous step.
3. Find 100% (original amount) by multiplying your answer in step 2 by 100.
<100% Example:
A shop is having a sale where all items are 30% off.
An item is on sale for $84.
What was the original price of the item?
100% - 30% = 70% of the original price
@codenickycode
codenickycode / sleep.ts
Last active December 30, 2022 17:38
[TS: Sleep Function] A Promise that resolves after ms argument #typescript
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
@codenickycode
codenickycode / useGoBackBrowserSync.tsx
Last active December 30, 2022 21:13
[React: Browser/Router Sync] Sync the browser's back button with react-router history.goBack #react #browser #router
function useGoBackBrowserSync() {
useEffect(() => {
return history.listen((newLocation, action) => {
if (action === 'POP') {
history.goBack();
}
});
}, [history]);
}