JavaScript Code Snippets

Suspend a Promise

A function that "suspends" a Promise, or accepts a Promise and makes it compatible with Suspense.To use this, call this function with your desired Promise as the argument.It will return an object.To get the resolved value, call read() on this object.

Something along the lines of const myResource = suspend(fetch('/value.json')).const value =

Save Binary File

This function lets you prompt the user for downloading a binary file to their device.I'm not sure how it handles endianness.

Save Text File

This function lets you prompt the user for downloading a text file to their device.

Leading Debounce a Function

Like the below function, except this executes on the first invocation and debounces subsequent invocations until the timeout is satisfied.

Debounce a Function

Adapted from Ondrej Polesny's article on the topic, this function lets you debounce the execution of the function that's passed as an argument. For example, writing const mashButton = debounce(() => console.log('thanks for waiting'), 500) lets you repeatedly call mashButton.It will debounce the log function until 500 milliseconds have passed without the function being called again.After 500 milliseconds, the log function will be invoked.

A N-ary Tree Node

An ES6 class that defines a node for use in discrete trees.It makes very few assumptions other than that it's designed for tree structures, so you can extend it for more specific tree applications. A good practice is to add functions that operate on these nodes and their descendants as static functions of the node class. For example, serializeTree below should be called as TreeNode.serializeTree(someNode).This way, it's apparent to developers how nodes are treated, and you can still take advantage of polymorphism.

Clamp a Number

A function that clamps a number between two values.

Custom Event Emitter

A simple event emitter for use in Observer patterns.Adapted from Eric Muyser's Stack Overflow answer.

Simple PWA Service Worker

A very small service worker ready for use in a Progressive Web App.

Map a Number from One Range to Another

The function is called scale, because map is often associated with the array function in the context of JavaScript.Borrowed from August Miller.

Keyboard Manager (Game Dev)

A class that provides an easy-to-use interface for using a hardware keyboard as input in a game.Specifically, it's meant to be instantiated outside of the game loop so that its functions can be called in the game loop.This way, the game can update based on the keyboard state on each tick.

Gamepad Manager (Browser)

A class that provides an easier-to-use interface for interacting with gamepads like PlayStation and XBox controllers.This class assumes the controller has a standard control mapping. Construct it outside of the game loop, and call its member functions on each tick in the loop.Only call its functions when the instance's ready() function returns true. See this, this, and this.

Check Whether the Current Browser has an Ethereum Wallet

This function returns a boolean value determining whether the current browser has a Web3 wallet available.It returns true if the wallet is available and false if it isn't.

Send Ether to an Address

A quick-and-dirty way to send Ether to an Ethereum address.It's compatible with all of the EIP-1102 implementations and older Web3 browser implementations.This function accepts the recipient address as a string and the hex-encoded amount in Wei to send as a string.It returns a promise that resolves to the transaction receipt or hash, depending on the Web3 version used.

Request Access to an Ethereum Wallet

A quick-and-dirty way to request access to a user's Ethereum wallet within the browser.It returns 'allowed' if the user gives access, 'denied' if the user denies access, and 'no-wallet' if the user doesn't have a Web3 wallet.

Promisify a Function Accepting a Callback

Turn a function that accepts a callback function as a argument into another that returns a Promise. Here, someFunction accepts a callback as the second argument.somePromisifiedFunction is the promisified version of someFunction.

Detect Dark Mode in the Browser

Detect dark mode and changes to dark mode in the browser in JS, when CSS isn't enough.

Send a Single SMS Message (Twilio)

To run this Node.js script, the Twilio JavaScript library must first be installed.Here, sendingNumber and receivingNumber include the country code. Note that the Account SID and Auth Token are provided to the script as environment variables.You can find these values in your Twilio dashboard.

Node.js Unit Testing (Jest)

The structure of a test suite in Node.js.First, Jest must be installed. This code should be in a file titled mytest.test.js, and it can be ran by executing the jest command in the terminal.

Linear Interpolation (lerp)

A simple lerp implementation.progress ranges from 0 (start) to 1 (end).

Generate list of numbers in range

Like Python's range function, this returns an array of numbers, starting from the given initial value, and increments by step, and stops before the given final value. If the optional boolean parameter inclusiveOfB is set to true, this function will include the given final value at the end of the returned array.

Slugify a String

Turn a string into a slug.Borrowed from Lulu.