pete's notebooks

  • Redux-Pine - /pete/redux-pine
    Last edited 5 years ago
    const redux = require('redux'); const createStore = redux.createStore; function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 case 'DOUBLE': return state * 2; case 'HALVE': return state / 2; default: return state } } let store = createStore(counter) store.subscribe(() => console.log(store.getState())) store.dispatch({ type: 'INCREMENT' }) store.dispatch({ type: 'INCREMENT' }) store.dispatch({ type: 'DECREMENT' })
  • Playlist Algorithm - /pete/playlist-algorithm
    Last edited 5 years ago
    const chai = require('chai'); const expect = chai.expect; let currentTime = 1; function now() { return currentTime; } const LOOP_MAX = 10000; function getCurrentTrackState(playlist) { let currentPoint = Number(playlist[0].addedAt); let loopIteration = 0; let i = 0; while (true) { const track = playlist[i]; loopIteration++; if (loopIteration > LOOP_MAX) { throw new Error(`Max iterations reached: ${currentPoint}`); } if (Number(track.addedAt) <= currentPoint) { currentPoint += track.trackLength; if (currentPoint > this.now()) { return { currentTrack: track, currentTrackOffset: this.now() - (currentPoint - track.trackLength), currentTrackIndex: i, nextTrack: playlist[(i + 1) % playlist.length] }; } else { i = (i + 1) % playlist.length; } } else { // Reset i to 0 (-1 + 1 for the end of the loop) i = 0; } } }
  • Validator - /pete/validator
    Last edited 6 years ago
    function validate(model, value) { const missingKeys = Reflect.ownKeys(model) .map((key) => { if (typeof model[key] === 'object') { const childKey = validate(model[key], value[key]); return childKey ? `${key}.${childKey}` : undefined } else if (model[key] && typeof value[key] === 'undefined') { return key; } }) .filter((key) => Boolean(key)); return missingKeys; }
  • Spying on Properties - /pete/spying-on-properties
    Last edited 7 years ago
    const DEFAULT_CALLBACK = (val, identifier) => console.log(`[${identifier}] Setting val: ${val}`); /** * Spies on a property of an object, gives the object a random identifier, and * calls an optional callback whenever the value is set. * * @param {any} on - The object to spy on * @param {string} prop - The name of the property to spy on */ function spy(on, prop, callback=DEFAULT_CALLBACK) { const rand = Math.random(); on.__rand = rand; Object.defineProperty(on, prop, { get: () => { return on[`__${prop}`]; }, set: (val) => { DEFAULT_CALLBACK(val, rand); on[`__${prop}`] = val; } }); }
  • TypeDoc - /pete/typedoc
    Last edited 7 years ago
    const _td = require('type-doc').main; const TypeDoc = (file) => _td(file, false, { strictClassChecks: true });
  • Underscore range is silly. - /pete/underscore-range-is-silly
    Last edited 7 years ago
    const _ = require('underscore'); const range1 = _.range(1, 3); _(range1).map((i) => i)
  • TypeDoc v0.1.40 - /pete/typedoc-2
    Last edited 7 years ago
  • Dynamic Circle PayTo Code - /pete/dynamic-circle-payto-code
    Last edited 7 years ago
    const express = require("@runkit/tonic/express-endpoint/1.0.0"); const app = express(module.exports); const bodyParser = require('body-parser'); const crypto = require('crypto'); function generateLink(sender, message) { const paymentURL = `circle:${sender}?message=${message}`; return `https://www.circle.com/send?paymentURL=${encodeURIComponent(paymentURL)}`; } const TX_ID_LENGTH = 7; app.use(bodyParser.urlencoded({ extended: false })); app.get('/generate', (req, res) => { const email = req.query.email; let message = req.query.message; if (!message) { const randomTxId = crypto.randomBytes(Math.ceil(TX_ID_LENGTH/2)) .toString('hex') .slice(0, TX_ID_LENGTH); message = `Thanks for supporting ${email}! txid: ${randomTxId}`; } const link = generateLink(email, message); res.send(` <html> <body style="padding: 40px"> <a href="${link}"> ${link} </a> </body> </html> `); }); 0;
  • Bluebird - /pete/bluebird
    Last edited 7 years ago
    const Promise = require('bluebird'); await Promise.resolve() .then(() => { throw new Error('oopsie'); }) .finally((results) => { console.log('results:', results); }) .catch((e) => 'eat the error') .then(() => 'poopsie');
  • Moar Promises - /pete/moar-promises
    Last edited 7 years ago
    await Promise.resolve() .then(() => { return Promise.resolve() .then(() => { throw new Error('poop') }); }) .catch((e) => `Don't worry I caught it`);