Skip to content

Instantly share code, notes, and snippets.

Avatar
🤖

Seth Davis sethdavis512

🤖
View GitHub Profile
@sethdavis512
sethdavis512 / Switchboard.tsx
Last active Dec 9, 2022
A component that only shows one of its children and allows dynamic switching between children
View Switchboard.tsx
import React, {
useContext,
createContext,
ReactNode,
useMemo,
Children,
isValidElement,
useState
} from 'react';
View encode-object-params.js
const encodeGetParams = p =>
Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");
const params = {
user: "María Rodríguez",
awesome: true,
awesomeness: 64,
"ZOMG+&=*(": "*^%*GMOZ"
};
@sethdavis512
sethdavis512 / custom-file-generator-cli-tutorial.md
Last active Oct 9, 2022
Custom File Generator CLI Tutorial
View custom-file-generator-cli-tutorial.md

Custom File Generator CLI Tutorial

As a developer who works on multiple React projects daily, I like having a tool that can help me quickly and efficiently write consistent code. One of the best ways I've found is writing a custom command line tool to rapidly scaffold out my most common code patterns.

My tool of choice is Plop.js. Plop is a powerful "micro-generator framework" built to help maintain patterns as well as speed up your project build time. From the documenation:

If you boil plop down to its core, it is basically glue code between inquirer prompts and handlebar templates.

In this tutorial, we'll build out a simple React component generator for your Typescript projects. By the end, you'll have a fully functioning CLI that is customized to your file generating needs. Let's get started.

@sethdavis512
sethdavis512 / readAndWrite.tsx
Created Sep 11, 2020
Node read and write async functions
View readAndWrite.tsx
const read = async (filePath: string) => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err: any, data: string) => {
if (err) reject(err)
resolve(data)
})
})
}
const write = (filePath: string, fileName: string, fileExtension: string, content: any) => {
View getUniqueId.js
const getUniqueId = (prefix) => `${prefix}-${Math.random().toString(36).substr(2, 9)}`;
View .prettierrc
{
"arrowParens": "avoid",
"semi": false,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "none"
}
View distribute.js
const itemList = [
{ type: 'TRIANGLE', color: 'RED' },
{ type: 'TRIANGLE', color: 'BLUE' },
{ type: 'SQUARE', color: 'GREEN' },
];
const bucketList = [
{
name: 'TRIANGLES',
condition: (i) => i.type === 'TRIANGLE'
View toPascalCase.ts
import upperFirst from 'lodash/upperFirst';
import camelCase from 'lodash/camelCase';
export function toPascalCase(srcString: string): string {
return upperFirst(camelCase(srcString));
};
View toConstant.ts
const toConstant = (str: string): string => str.replace(/\s+/g, '_').toUpperCase();
View pickRandom.js
const pickRandom = (arr) => arr[Math.floor(Math.random() * arr.length)];