Skip to content

Instantly share code, notes, and snippets.

View donavon's full-sized avatar
🏁
nothing is happening

Donavon West donavon

🏁
nothing is happening
View GitHub Profile
@donavon
donavon / js-quiz-2.js
Created February 28, 2022 02:40
JS Quiz #2
/*
Write a function to flatten any object such that the flatten keys are a camelCased
concatination of the key and all parent keys. If the value is an array, name the key with the
position of the array (base 1) and remove the plural "s" (assume all arrays end with an "s").
Should work with infinite layers, not just two. Arrays can contain objects.
In the example `user` below, the output would be as follows:
{
nameFirst: 'John',
nameLast: 'Doe',
@donavon
donavon / useTrackPageView.ts
Created October 23, 2021 14:31
onLocationChange isn't being called
// set page tracking for Single Page Applications
// see https://developers.google.com/analytics/devguides/collection/gtagjs/single-page-applications
import { createBrowserHistory, Update } from 'history'; // 5.0.1
import { useEffect } from 'react';
const history = createBrowserHistory();
const onLocationChange = ({ location }: Update) => {
const { gtag } = window;
@donavon
donavon / useKeyDown.ts
Created March 15, 2021 22:03
A custom #ReactJS hook that listens for changes in the state of any key.
import { useState, KeyboardEvent } from 'react';
import useEventListener from '@use-it/event-listener';
export const useKeyDown = (key: string) => {
const [keyDown, setKeyDown] = useState(false);
useEventListener('keydown', (ev: KeyboardEvent) => {
if (ev.key === key) {
setKeyDown(true);
}
@donavon
donavon / github-users.js
Created March 11, 2021 14:02
Maps over an array of Github usernames and returns an array of user objects.
const githubUsernames = ['donavon', 'revelcw', '#^%$', 'sessionsfm'];
const fetchGithubUser = async (username) => {
const resp = await fetch(`https://api.github.com/users/${username}`);
return resp.ok ? await resp.json() : null;
}
const users = await Promise.all(
githubUsernames.map(fetchGithubUser)
);
@donavon
donavon / someFunction.ts
Created March 6, 2021 11:27
TypeScript
const someFunction = (arg: string | string[]) => {
if (Array.isArray(arg)) {
return arg.map<string>(someFunction);
}
return arg.toUpperCase();
};
const x = someFunction('a'); // should be type string
const arr = someFunction(['a']); // should be type string[]
@donavon
donavon / formData.js
Last active February 17, 2021 07:29
Here's a good, better, best approach to convert a JavaScript object to "application/x-www-form-urlencoded" postable form data.
const formData = { foo: "foo", bar: "M&Ms" };
// Good 🔥
const postBody = Object.keys(formData)
.map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(body[key]))
.join("&");
// Better 🔥🔥
const postBody = Object.entries(formData)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
@donavon
donavon / segmentize-regexp.ts
Last active January 30, 2021 15:58
segmentize
const segmentize = (str: string, maxLength: number): string[] => {
const regex = new RegExp(`.{1,${maxLength}}`, 'g');
return str.match(regex) ?? [];
};
@donavon
donavon / typescriptreact.json
Last active January 22, 2021 11:04
A VSCode shortcut to create a new React Function Component
{
"tsx": {
"prefix": "tsx",
"description": "Create a TypeScript React Function Component",
"body": [
"import React from 'react';",
"",
"type ${1:MyComponent}Props = {",
" children: React.ReactNode;",
"};",
@donavon
donavon / Order.tsx
Created October 15, 2020 10:18
Naming is hard — Order
import React from "react";
import { OrderProps } from "./OrderProps.types";
export const Order = ({ order }: OrderProps) => {
return <div>...</div>;
};
@donavon
donavon / MyComponent.js
Created April 7, 2020 13:57
StateRouter for rendering one or more children where `state` is found in the`path` prop.
// Example component using StateRouter
const MyComponent = () => {
const [state] = useMachine(myMachine);
return (
<StateRouter state={state}>
<Loading path="loading" />
<Ready path="ready" />
<Error path="error" />