rahat's notebooks

  • async observable from generator? - /rahat/async-observable-from-generator
    Last edited 7 years ago
    const Rx = require("rx") // Pretend this is a generator that is useful // 'abc' -> ['a', 'ab', 'abc'] function* Generator (str) { for(var i = 0; i < str.length; i++) { yield str.substr(0, i + 1) } } Rx.Observable.of('ab', 'xy') .concatMap((line, index) => // How to read from generator asynchronously (once per tick, or so) Rx.Observable.from(Generator(line), null, null, Rx.Scheduler.async) .map(text => ({ text, index })) ) .subscribe(({text, index}) => { // this.state.chapter[index] = text console.log(val) })
  • tonic + npm: number-abbreviate - /rahat/number-abbreviate
    Last edited 7 years ago - from: https://tonicdev.com/npm/number-abbreviate
    var numAbbr = require('number-abbreviate')() // It should assume decimal place of 0 numAbbr.abbreviate(1234)
  • Binding null - /rahat/binding-null
    Last edited 7 years ago
    var context = { fn() { return this.x; }, x: 'local context' }
  • toJSON - /rahat/tojsontest
    Last edited 7 years ago
    var _ = require('lodash'); function MyClass() { this.a = Math.random(); this.dontSerializeMeBro = Math.random(); } MyClass.prototype.toJSON = function() { return _.omit(this, 'dontSerializeMeBro'); } JSON.stringify(new MyClass())
  • Premature Unhandled Rejection Error - /rahat/premature-unhandled-rejection-error
    Last edited 7 years ago
    Lesson learned: If you catch a rejected promise in a future tick, there's no way for the browser/polyfill to know it's not an unhandled rejection.
  • Lint all of a user's package.json's - /rahat/lint-all-of-a-user-s-package-json-s
    Last edited 7 years ago
    const USER = 'rahatarmanahmed' const Linter = require("npm-package-json-lint/src/NpmPackageJsonLint") const getUsersPackages = require("npm-user-packages") const getPackage = require('package-json') const url = require('url') const config = { 'require-author': 'error', 'require-bugs': 'error', 'require-description': 'error', 'require-homepage': 'error', 'require-keywords': 'error', 'require-license': 'error', 'require-repository': 'error', 'require-name': 'error', 'require-version': 'error', 'name-format': 'error', 'version-format': 'error', 'bin-type': 'error', 'config-type': 'error', 'cpu-type': 'error', 'dependencies-type': 'error', 'description-type': 'error', 'devDependencies-type': 'error', 'directories-type': 'error', 'engines-type': 'error', 'files-type': 'error', 'homepage-type': 'error', 'keywords-type': 'error', 'license-type': 'error', 'main-type': 'error', 'man-type': 'error', 'name-type': 'error', 'optionalDependencies-type': 'error', 'os-type': 'error', 'peerDependencies-type': 'error', 'preferGlobal-type': 'error', 'private-type': 'error', 'repository-type': 'error', 'scripts-type': 'error', 'version-type': 'error' } const getPackageNames = user => { return getUsersPackages(user) .then(pkgs => pkgs.map(pkg => pkg.name)) } const lintPackage = (pkg, res) => { const results = new Linter(pkg, config, {}).lint() if(results.errors.length) res.write('\n' + pkg.name + '\n') results.errors .map(issue => res.write('\t' + issue + '\n')) } const getQuery = req => url.parse('' + req.url, true).query exports.tonicEndpoint = (req, res) => { if(!getQuery(req).user) return res.end('You need to provide a `user` url query parameter') getPackageNames(getQuery(req).user) .then(pkgs => Promise.all(pkgs.map(name => getPackage(name, 'latest')))) .then(pkgs => Promise.all(pkgs.map(pkg => lintPackage(pkg, res)))) .catch(console.error.bind(console)) }
  • Random Workplace Fatality - /rahat/random-workplace-fatalities
    Last edited 7 years ago
    const CSV_URLS = [ "https://www.osha.gov/dep/fatcat/FatalitiesFY09.csv", "https://www.osha.gov/dep/fatcat/FatalitiesFY10.csv", "https://www.osha.gov/dep/fatcat/FatalitiesFY11.csv", // "https://www.osha.gov/dep/fatcat/FatalitiesFY12.csv", // This CSV has bad headers "https://www.osha.gov/dep/fatcat/fy13_federal-state_summaries.csv", "https://www.osha.gov/dep/fatcat/fy14_federal-state_summaries.csv", "https://www.osha.gov/dep/fatcat/fy15_federal-state_summaries.csv", ]; const got = require('got') const csvStream = require("csv-stream") const through2 = require("through2") const rand = require("rand-stream") const makePage = (fatality) => ` <!doctype html> <html> <head> <title>Random Workplace Fatality</title> <style> html, body { height: 100%; width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; } </style> </head> <body> <h1 class="fatality">${fatality}</h1> <a href="" onclick="window.reload()">Next Random Fatality</a> </body> </html> ` exports.tonicEndpoint = function(req, res) { const CSV_URL = CSV_URLS[3] got.stream(CSV_URL) .pipe(csvStream.createStream({ escapeChar : '"', enclosedChar : '"' })) .pipe(through2.obj((chunk, enc, cb) => { cb(null, chunk['Preliminary Description of Incident']) })) .pipe(rand(1)) .on('data', (fatality) => res.end(makePage(fatality))) }
  • ohhellyeah - /rahat/ohhellyeah
    Last edited 7 years ago
    const ohhellyeah = require('ohhellyeah') exports.tonicEndpoint = function(req, res) { res.end(ohhellyeah()) }
  • string-hash case insensitivity - /rahat/string-hash-case-insensitivity
    Last edited 7 years ago
    const hash = require("string-hash") const Chance = require('chance') const chance = new Chance() // If you mod the hashes by a power of 2 up to 32, different case strings hash the same? const MOD = 16; console.log('name -- normal -- lowercase -- uppercase') for(var k=0; k<5; k++) { let name = chance.name() let normalHash = hash(name) % MOD let lowerHash = hash(name.toLowerCase()) % MOD let upperHash = hash(name.toUpperCase()) % MOD console.log(name + ' -- ' + normalHash + ' -- ' + lowerHash + ' -- ' + upperHash) }
  • StarWarsIntroCreator for PRs - /rahat/star-wars-pr-intro
    Last edited 7 years ago - from: https://tonicdev.com/npm/got
    var got = require("got"), romanize = require('romanize'); exports.tonicEndpoint = (req, res) => { var parsedUrl = require('url').parse(req.url, true) var url = parsedUrl.query.url || parsedUrl.query.pr; if(!url) return res.end('Must provide `url` query parameter'); var prInfo; var match = url.match(/github\.com\/(.+?)\/(.+?)\/pull\/(\d+)(?:\/|$)/); var user = match[1]; var repo = match[2]; var pr = match[3]; var prUrl = 'https://api.github.com/repos/' + user + '/' + repo + '/pulls/' + pr; got(prUrl, { json: true }) .then(response => { prInfo = response.body; return got(prInfo.diff_url) }) .then(response => { var diff = response.body; var title = prInfo.title; var episode = user + '/' + repo + ' Episode ' + romanize(pr); var opts = { json: true, method: 'POST', body: JSON.stringify({ intro: "A long time ago, in a pull request far,\nfar away....", episode: episode, title, title, text: diff }) }; return got('https://starwarsopening.firebaseio.com/openings.json', opts); }) .then(response => { res.writeHead(302, { Location: 'http://brorlandi.github.io/StarWarsIntroCreator/#!/' + response.body.name.substring(1) }); res.end(); }); };