Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Snippets
// *REALLY* hate Ternary syntax or && in your JSX rendering? Try this handy function.
const ifTruthyThen = <T>(predicate: any, value: T): T | null => {
if(!predicate){
return null;
}
return value;
}
// usage
const Component = ({chimichanga}: any) => {
return <div>
{/* If this way looks ugly to you:
{ chimichanga && <TexMex value={chimichanga}/> }
and you REALLY hate ternaries:
{ chimichanga ? <TexMex value={chimichanga}/> : null }
then try this:
/*}
{ifTruthyThen(chimichanga, <TexMex value={chimichanga}/>)}
</div>
}
// returns true if window does not exist, i.e., we are serverside.
import windowExists from './windowExists.ts'
const isIe11: () => boolean = (() => {
let isIE: boolean; // set only once and locked via closure;
let determined: boolean; // set only once and locked;
return () => {
// we already know whether this is IE or not.
if (determined) {
return isIE;
}
// there's no window yet - maybe we're SSRed.
if (!windowExists()) {
return false;
}
isIE = /Trident/gi.test(window.navigator.userAgent);
determined = true;
return isIE;
};
})();
const windowExists = (): boolean => !(typeof window === typeof undefined);
const withLoggedPerformance = (() => {
const logs: Record<string, number> = {};
return (fn: Function) => (...args: any[]) => {
const startTime: number = performance.now();
const resolution = fn(...args);
const duration = performance.now() - startTime;
const functionName = fn.name;
if (!functionName) {
console.info(`Anonymous function took ${duration}ms`);
} else {
if (logs[functionName] === undefined) {
logs[functionName] = 0;
}
logs[functionName] += 1;
console.info(`Execution #${logs[functionName]} of ${fn.name} took ${duration}ms`);
}
return resolution;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.