Skip to content

Instantly share code, notes, and snippets.

@jcready
jcready / parseGraphAndFindNodesWhichCanReachAGivenNode.js
Created February 22, 2018 22:25
Parse stringified graph (‘a->b,b->c, a->c’) and find all the nodes that can reach a given node
export const parseGraph = s => s
.split(',')
.map(edge => edge.trim().split('->'))
.reduce((adjacency, [a, b]) => {
if (!adjacency.has(a)) {
adjacency.set(a, new Set())
}
if (!adjacency.has(b)) {
adjacency.set(b, new Set())
}
@jcready
jcready / PriorityQueue.js
Created February 18, 2018 18:22
A priority queue using a private binary heap
const PriorityQueue = (() => {
const parent = i => ((i + 1) >>> 1) - 1
const left = i => (i << 1) + 1
const right = i => (i + 1) << 1
const privateMap = new WeakMap()
const $ = privateMap.get.bind(privateMap)
const swap = (self, i, j) => {
const h = $(self).heap
isBalanced = (() => {
const braces = {
'{': [ 0, 1 ],
'}': [ 0, -1 ],
'[': [ 1, 1 ],
']': [ 1, -1 ],
'(': [ 2, 1 ],
')': [ 2, -1 ]
}
return function isBalanced (s) {
@jcready
jcready / integration.async.await.js
Last active May 13, 2017 17:35
Node.js example of GitHub Integration auth process
// With async/await support
const fs = require('fs')
const jwt = require('jwt-simple')
const pem_file = '/path/to/github.pem' // the absolute path to your Application Pem Certificate issued by GitHub
const integration_id = 0 // GitHub Application Integration ID
const installation_id = 0 // once installed on an organization. The Organization Integration ID
const expire_seconds = 60 // number of seconds the jwt token expires (max ~600 but not designated by GitHub)
const slug = 'owner/repo' // name of repo for demo purposes
const privateKey = fs.readFileSync(pem_file)
(function(){
const EE = require('events')
const Stream = require('stream')
const promise = Symbol('StreamPromise')
Stream.prototype.constructor = function () {
EE.call(this)
this[promise] = new Promise((resolve, reject) => {
this.on('error', reject)
this.on('end', resolve)
@jcready
jcready / typeof.js
Last active April 12, 2016 16:09
Better typeof() Function
var typeOf = (function(_, g, u) {
return function(o) {
return o === g
? 'global'
: o == u
? o === u
? 'undefined'
: 'null'
: o !== o
? 'NaN'
a2p addr2line animate appletviewer8 ar as aserver awk base64 bashbug bashbug-64 bdftopcf bdftops berkeley_db_svc bmp2tiff build-classpath build-classpath-directory build-jar-repository bunzip2 bzcat bzcmp bzdiff bzgrep bzip2 bzip2recover bzless bzmore c++filt c2ph ca-legacy cairo-sphinx cal captoinfo catchsegv certutil chcon check-binary-files chrt chvt cksum clean-binary-files clear cmp cmsutil col colcrt colrm column comm compare composite conjure convert create-jar-links crlutil csplit curl cut d8 db_archive db_checkpoint db_codegen db_deadlock db_dump db_dump185 db_hotbackup db_load db_printlog db_recover db_stat db_upgrade db_verify deallocvt diff diff-jars diff3 dir dircolors dirname display du dumphint dvipdf dwp eject elfedit env eps2eps eqn eu-addr2line eu-ar eu-elfcmp eu-elflint eu-findtextrel eu-make-debug-archive eu-nm eu-objdump eu-ranlib eu-readelf eu-size eu-stack eu-strings eu-strip eu-unstrip expand expr extcheck8 factor fallocate fax2ps fax2tiff fc-cache fc-cat fc-list fc-match fc-query fc-s
@jcready
jcready / MediaElementSource.js
Last active December 27, 2015 02:39
Processing Web Audio ChannelData from MediaElementSource.
var audioContext, audioProcess, audioSource,
result = document.createElement('h3'),
output = document.createElement('span'),
mp3 = 'http://songs.jonathancoulton.com/mp3/First%20of%20May.mp3',
ogg = 'http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg',
gotData = false, data, audio = new Audio();
function connect() {
audioContext = window.AudioContext ? new AudioContext() : new webkitAudioContext(),
audioSource = audioContext.createMediaElementSource( audio ),
@jcready
jcready / mediaMatch.js
Last active December 20, 2015 09:09
Winamp Toolbar's "Media Match" functionality duplicated in plain JavaScript.
(function(){
var links = document.getElementsByTagName('a'),
audio = document.getElementsByTagName('audio'),
media = [],
match = /\.(m3u|pls|smil|aac|aif|alac|flac|ogg|mpa|mp3|mp4|m4a|wav|wma)$/i;
for (var i = 0; i < links.length; i++)
if (match.test(links[i].pathname))
media.push(links[i].href)
for (var i = 0; i < audio.length; i++)
if (match.test(audio[i].src))
navigator.geolocation.watchPosition(function(g){
if (g.coords.latitude === null && g.coords.longitude === null) return;
var c = g.coords, l = { acc: c.accuracy };
if (c.latitude !== null) l.lat = ~~(c.latitude*10000)/10000;
if (c.longitude !== null)l.long = ~~(c.longitude*10000)/10000;
if (c.speed !== null) l.speed = c.speed;
if (c.heading !== null && !isNaN(c.heading)) l.dir = c.heading;
if (c.altitude) { l.alt = c.altitude; l.altacc = c.altitudeAccuracy }
console.log(l);
});