Skip to content

Instantly share code, notes, and snippets.

💭
Copying and pasting from StackOverflow

Cameron Nokes ccnokes

💭
Copying and pasting from StackOverflow
Block or report user

Report or block ccnokes

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
@ccnokes
ccnokes / axios-instance-config.js
Created Jul 6, 2017
Good default configuration for axios in node.js
View axios-instance-config.js
const axios = require('axios');
const http = require('http');
const https = require('https');
module.exports = axios.create({
//60 sec timeout
timeout: 60000,
//keepAlive pools and reuses TCP connections, so it's faster
httpAgent: new http.Agent({ keepAlive: true }),
@ccnokes
ccnokes / rx-online-offline.js
Last active Nov 8, 2019
Online/offline event observable with RxJS (see comments below for a better, more up-to-date way of doing this)
View rx-online-offline.js
const { Observable } = require('rxjs/Observable');
require('rxjs/add/observable/fromEvent');
require('rxjs/add/operator/map');
require('rxjs/add/observable/merge');
function createOnline$() {
//merge several events into one
return Observable.merge(
//use .map() to transform the returned Event type into a true/false value
Observable.fromEvent(window, 'offline').map(() => false),
@ccnokes
ccnokes / ObservableMap.ts
Last active Nov 5, 2019
A Map class with built-in event emitter that emits a `update` event whenever something changes
View ObservableMap.ts
class ObservableMap<K, V> extends Map<K, V> {
readonly events = new EventEmitter();
set(key: K, value: V) {
let previousValue = this.get(key);
super.set(key, value);
this.events.emit("update", {
key,
action: "set",
previousValue,
currentValue: this.get(key)
View event-emitter.js
class EventEmitter {
constructor() {
this.target = new EventTarget();
}
on(eventName, listener) {
return this.target.addEventListener(eventName, listener);
}
once(eventName, listener) {
return this.target.addEventListener(eventName, listener, { once: true });
}
@ccnokes
ccnokes / event-emitter.js
Created Oct 30, 2019
Event emitter using the native DOM APIs: EventTarget and CustomEvent
View event-emitter.js
// Who needs eventemitter3, mitt, or some other library when you can use native DOM APIs? 😁
let eventEmitter = new EventTarget();
eventEmitter.addEventListener('test', console.log); // CustomEvent { type: 'test', detail: 123, ... }
eventEmitter.dispatchEvent(new CustomEvent('test', { detail: 123 }));
@ccnokes
ccnokes / Batch.ts
Last active Oct 2, 2019
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
View Batch.ts
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 / wait-with-abortsignal.js
Last active Sep 11, 2019
Use AbortController to implement custom async task cancelling logic. Expounded upon here: https://cameronnokes.com/blog/cancelling-async-tasks-with-abortcontroller/
View wait-with-abortsignal.js
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
Created Aug 22, 2019
Minimal AbortController implementation for node.js that doesn't have to shim DOM stuff
View AbortController.ts
import { EventEmitter } from 'events';
class AbortController {
private events = new EventEmitter();
aborted = false;
signal = {
get aborted() {
return this.aborted;
},
@ccnokes
ccnokes / idObj.ts
Last active Aug 22, 2019
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…
View idObj.ts
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 / preload-example.js
Created Feb 1, 2017
Electron preload script
View preload-example.js
// in preload scripts, we have access to node.js and electron APIs
// the remote web app will not have access, so this is safe
const { ipcRenderer: ipc, remote } = require('electron');
init();
function init() {
// Expose a bridging API to by setting an global on `window`.
// We'll add methods to it here first, and when the remote web app loads,
// it'll add some additional methods as well.
You can’t perform that action at this time.