Skip to content

Instantly share code, notes, and snippets.

View n8jadams's full-sized avatar

Nate Adams n8jadams

View GitHub Profile
@n8jadams
n8jadams / useBeforeClosingWindowPrompt.ts
Last active October 19, 2023 16:36
useBeforeClosingWindowPrompt - a hook that prompts user before they close the window when there are unsaved changes
import { useEffect } from "react";
/**
* A hook that prevents closing or refreshing if there are unsaved changes,
* offering the user a prompt to confirm before closing the window.
* @param promptBeforeClosingWindow A boolean indicating if we should prompt before closing
*/
export function useBeforeClosingWindowPrompt(promptBeforeClosingWindow: boolean) {
useEffect((): (() => void) => {
function handleBeforeUnload(e: BeforeUnloadEvent): void {
@n8jadams
n8jadams / webpack.config.js
Created October 28, 2022 17:39
Split up vendors into smaller chunks
// The best way to split up your npm deps into smaller chunks
module.exports = (env) => {
const config = {
// ... rest of config options
optimization: {
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
vendors: {
@n8jadams
n8jadams / downloadObjectAsJSONFile.ts
Last active August 19, 2022 21:11
Download a javascript object as a JSON file
async function downloadObjectAsJSONFile(object: any, filename: string): Promise<void> {
if(!filename.endsWith('.json')) {
filename = `${filename}.json`
}
const json = JSON.stringify(object)
const blob = new Blob([json],{ type:'application/json' })
const href = await URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = href
link.download = filename
@n8jadams
n8jadams / downloadTextAsFile.ts
Created August 19, 2022 21:09
Download plaintext as a file
async function downloadTextAsFile(text: string, filename: string): Promise<void> {
if (!filename.endsWith(".txt")) {
filename = `${filename}.txt`;
}
const blob = new Blob([text], { type: "text/plain" });
const href = await URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = href;
link.download = filename;
link.style.position = "absolute";
@n8jadams
n8jadams / remove-all-css-from-page.js
Created April 30, 2022 01:55
A quick script to remove all styling from a website
document.querySelectorAll('style, link[rel="stylesheet"]').forEach(el => el.parentNode.removeChild(el))
document.querySelectorAll('[style]').forEach(el => el.style = null)
@n8jadams
n8jadams / parse-query-string.js
Created April 30, 2022 01:53
Parse query string. (Just use URLSearchParams instead of this)
function parseQueryString(query) {
query = query.substring(query.indexOf('?') + 1);
let re = /([^&=]+)=?([^&]*)/g;
let decodeRE = /\+/g;
let decode = function(str) {
return decodeURIComponent(str.replace(decodeRE, ' '));
};
@n8jadams
n8jadams / not-function.js
Created April 29, 2022 21:59
not(someFunction(someArgs))
const not = fn => (...args) => !fn.apply(null, args)
@n8jadams
n8jadams / csv-string-to-arr-of-objs.js
Created April 29, 2022 21:47
Convert a CSV string to an array of objects
function csvStringToArrOfObjs(csvString) {
const rowsWithColumNames = csvString.split('\n')
const columnNames = rowsWithColumNames[0].split(',').map(columnName => columnName.replace('\r', ''))
const rows = rowsWithColumNames.slice(1)
return rows.map(row => {
const obj = {}
const parts = row.split(',').map(columnName => columnName.replace('\r', ''))
columnNames.forEach((columnName, index) => {
obj[columnName] = parts[index]
})
@n8jadams
n8jadams / copy-to-clipboard.js
Last active August 19, 2022 20:56
Copy some text to the clipboard
// Newer and preferred way
function copyToClipboard(text) {
navigator.clipboard.writeText(text)
}
// Support on old browsers
function copyToClipboard(text) {
const tmpInput = document.createElement('input')
tmpInput.value = text
tmpInput.type = 'text'
@n8jadams
n8jadams / read-inputs-cli.js
Last active February 9, 2023 18:20
Read in non-hidden and hidden inputs in a cli
const readline = require("readline");
const question = (query) =>
new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(`${query}\n`, (value) => {
rl.close();