Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View ccnokes's full-sized avatar

Cameron Nokes ccnokes

View GitHub Profile
@ccnokes
ccnokes / wait-with-abortsignal.js
Last active February 12, 2021 13:50
Use AbortController to implement custom async task cancelling logic. Expounded upon here: https://cameronnokes.com/blog/cancelling-async-tasks-with-abortcontroller/
function wait(ms, opts = {}) {
return new Promise((resolve, reject) => {
let timerId = setTimeout(resolve, ms);
if (opts.signal) {
// implement aborting logic for our async operation
opts.signal.addEventListener('abort', event => {
clearTimeout(timerId);
reject(event);
});
}
@ccnokes
ccnokes / AbortController.ts
Last active March 24, 2020 20:46
Minimal AbortController implementation for node.js that doesn't have to shim DOM stuff
import { EventEmitter } from 'events';
class AbortSignal {
private events = new EventEmitter();
constructor(
private getIsAborted: () => boolean
) {}
get aborted(): boolean {
@ccnokes
ccnokes / idObj.ts
Last active August 22, 2019 19:35
Sometimes in React you need a unique `key` to represent an object's identity. Instead of generating an id when you fetch it from an API or generating an id on the fly or using indexes (both will lead to bugs), you can use this which gives you a stable, unique id for an object. Demo: https://codesandbox.io/s/nice-gauss-h424o. Demo with React: htt…
let map = new WeakMap(); // weakly holds all object refs (works in IE11+)
let n = 0; // global counter for ids
export function idObj(obj: any) {
if (map.has(obj)) {
return map.get(obj);
} else {
let key = String(++n);
map.set(obj, key);
return key;
@ccnokes
ccnokes / rafScheduler.ts
Created June 18, 2019 19:59
requestAnimationFrame scheduler
/**
* A function for batching RAFs together
*/
export default function RAFScheduler() {
let queue = [];
let rafId;
let scheduled = false;
const DURATION = 10;
return function scheduleRaf(cb: () => void) {
@ccnokes
ccnokes / stash_to_patch.sh
Created March 28, 2019 17:47
Convert all stashes to patches in a git repository
#!/bin/bash
stash_count=$(git stash list | wc -l)
i=0
while [[ $i -lt $stash_count ]]; do
git stash show -p stash@{$i} > "stash-$i.patch"
i=$(( $i + 1 ))
done
@ccnokes
ccnokes / Batch.ts
Last active October 2, 2019 21:19
A class that manages the logic of batching items together within a timeframe and then passing those items to a function. Sandbox: https://codesandbox.io/s/v86lv7k89l
class Deferred<Type> {
promise: Promise<Type>;
// TODO type these
resolve: any;
reject: any;
then: any;
catch: any;
constructor() {
this.promise = new Promise((resolve, reject) => {
@ccnokes
ccnokes / SparseList.ts
Created February 22, 2019 17:59
A data structure that wraps a sparse array. Useful for when you know the total size of a list and need to represent it in its full size, but are lazy loading in sections of it. Sandbox: https://codesandbox.io/s/yvrv97k879
class SparseList<T = any> {
private list: T[];
emptySlotsCount: number;
constructor(size: number) {
this.list = new Array(size);
this.emptySlotsCount = size;
}
get size() {
@ccnokes
ccnokes / RICScheduler.ts
Last active February 23, 2019 22:14
RequestIdleCallback scheduler. Create an instance and use it globally to ensure that tasks are efficiently run in as few requestIdleCallbacks as possible (as described here https://developers.google.com/web/updates/2015/08/using-requestidlecallback). Sandbox: https://codesandbox.io/s/r45rv9lv1o
class RICScheduler {
private queue: { task: () => void, id: number }[] = [];
private running = false;
private nextId = 0;
private ricId;
private id() {
return this.nextId++;
}
@ccnokes
ccnokes / withNgService.tsx
Last active February 19, 2019 19:04
withNgService HOC for injecting modules from Angular.JS's dependency injector into a React component
import * as React from 'react';
import hoistStatics from 'hoist-non-react-statics';
declare var angular: any;
let injector;
// NOTE you probably can't run this at the top level of a module because angular takes time to load and bootstrap
export default function getNgService<T = any>(serviceName: string): T {
if (!injector) {
@ccnokes
ccnokes / initContext.tsx
Created February 1, 2019 17:46
A function that returns a React.Context and a mapContextToProps HOC so that you can inject context onto props, like react-redux's `connect` function
import * as React from 'react';
const defaultMapper = (ctx) => ctx
export function initContext<CtxType>() {
const Context = React.createContext<CtxType | null>(null);
function mapContextToProps<Props>(Component: React.ComponentType<Props & CtxType>, mapper: (ctx: CtxType) => any = defaultMapper): React.ComponentType<Props> {
return (props: Props) => (
<Context.Consumer>
{(ctx) => <Component {...props} {...mapper(ctx)} />}