Skip to content

Instantly share code, notes, and snippets.

View crdrost's full-sized avatar

CR Drost crdrost

View GitHub Profile
@crdrost
crdrost / hacker_hiding.user.js
Created April 3, 2012 10:09
Hacker News Comment Hiding
// ==UserScript==
// @name Hacker News Comment Hiding
// @namespace http://drostie.org/
// @include https://news.ycombinator.com/item?id=*
// @include http://news.ycombinator.com/item?id=*
// ==/UserScript==
function repeat(element, selector, n) {
return n <= 0 ? element : repeat(element[selector], selector, n - 1);
}
@crdrost
crdrost / fibs.hs
Created October 20, 2012 16:44
The "O(1)" Fibonaccis algorithm
-- Golden pair data type; GP x y represents x + y phi where phi ** 2 = 1 - phi
data GoldenPair = GP { r :: Integer, phi :: Integer } deriving (Eq, Show)
-- (a + b phi) * (1 + 1 phi) = (a + b) + a phi so we have the Fibonacci relation directly.
instance Num GoldenPair where
(GP a b) + (GP c d) = GP (a + c) (b + d)
(GP a b) * (GP c d) = GP (k + b*d) (k - (a - b)*(c - d)) where k = a*c
fromInteger x = GP x 0
@crdrost
crdrost / fizzbuzz.lhs
Last active August 29, 2015 14:07
Custom guards for FizzBuzz in Haskell
Custom guards in Haskell
========================
In 2007, people changed their programming interview questions from complicated IQ-style questions to the new "FizzBuzz" style: give them a task which should be absurdly easy if you have ever programmed anything, but with one or two essential complications to prove that they have thought through the idea. The canonical example is:
* Write a program which prints the numbers from 1 to 100 in order, except instead of any number divisible by 3 it prints "Fizz" and instead of any number divisible by 5 it prints "Buzz". (When a number is divisible by both, it should print "FizzBuzz".)
This query tests for familiarity with the environment (e.g. in JavaScript you'll have to "print" to the DOM) and basic mathematics (what does "divisible" mean?) and logic (since it's not immediately in an if / else if / else format), but we assume that if you can do these things then you can do anything.
Some of the cooler answers use fall-through:
@crdrost
crdrost / visitor-direct-translation.lhs
Created May 19, 2016 16:54
Gang of Four patterns in Haskell
This example comes from the Wikipedia article:
https://en.wikipedia.org/wiki/Visitor_pattern
Our first indication of complexity is the fact that the MyInterface[] array requires rank 2 types:
> {-# LANGUAGE Rank2Types, MultiParamTypeClasses, FunctionalDependencies #-}
The multiparam type class and functional dependency is not part of the Wikipedia article proper,
and instead come because I saw myself writing an expression like:
@crdrost
crdrost / syncify-example.js
Last active June 2, 2016 17:47
In ES6, async code can already be written synchronously with generators and yield -- no need to wait for ES7's async and await.
"use strict";
/* This is mostly just an example workflow to illustrate how a combination of ES6 generators and promises
* fully allow you to write your asynchronous workflow in a single synchronous-looking block.
*
* Unlike most such workflows which give you a really short snippet that can hide all of the thornier
* problems, this one is approximated from some of my work at IntegriShield: this is all of the real
* stuff that an actual daemon might have to do: manage a queue or three of concurrent workloads; load
* each item of each queue in order; make a bunch of concurrent requests on each item; preprocess each
* of these requests; save preprocessed results to a cache in the database; if all of them have completed
* successfully, report success, or else report failure.
@crdrost
crdrost / routing.hs
Created September 17, 2016 16:39
How would ideal routing tables work?
module MyServer.Routes (route) where
import FictitiousRoutingLib
-- Can't decide if I'd rather embed this into do-notation or just use lists; seems like the type param
-- ends up being a phantom type in the end?
route :: HttpRouter x
route = do
-- one thing you always want is static serving of files:
dom "static.myapp.example.com" % staticServe "/var/www/staticAssets"
-- maybe also `(excludePatterns [] $ staticServe "...")` to specify "these things shall never be served from that dir."
@crdrost
crdrost / dirtree.js
Last active May 8, 2017 21:45
dirtree - shows you where you are in a filesystem tree and some of what's around
#!/usr/bin/env node
/* Copyright 2017 CR Drost.
*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of
* the MPL was not distributed with this file, uou can obtain one at https://mozilla.org/MPL/2.0/.
*/
const fs = require('fs'),
bold = text => '\u001b[1m' + text + '\u001b[22m',
@crdrost
crdrost / bidir-streams.js
Created January 12, 2018 13:12
Bidirectional streams inspired by @andrestaltz
//json interpolation for string subs. Just used in shape().
const in_json = (strs, ...vals) =>
strs[0] + vals.map((v, i) => JSON.stringify(v) + strs[i + 1]).join("");
// validate shape of an object having appropriate methods.
// PLEASE do this, using if() makes this sort of "that fn doesn't handle this particular event"
// unassertable, and that means that you have whole undebuggable pipelines where "somewhere in
// this pipeline that information gets lost, I don't know where!"
const shape = (obj, ...method_names) => {
const missing_methods = method_names.some(m => typeof obj[m] !== "function");
@crdrost
crdrost / test-validateRoutePath.js
Last active May 24, 2018 13:30
Tester for a validateRoutePath function that I released to nestjs/swagger.
const isUndefined = obj => typeof obj === 'undefined'
const validatePath = path => path.charAt(0) !== '/' ? '/' + path : path;
const pathToRegexp = require('path-to-regexp');
function validateRoutePathNew(path) {
if (isUndefined(path)) {
return '';
}
let pathWithParams = '';
for (const item of pathToRegexp.parse(path)) {
@crdrost
crdrost / description.md
Last active December 18, 2021 12:35
Itero-recursive algorithms.

Iterorecursive algorithms

Picture the following scene: you are in a job interview, and the interviewer defines a tree-based data structure and asks you to traverse it. You do a good quick job, maybe using recursion:

// provided by the interviewer: nonempty rose trees carrying the values on the internal nodes
interface ITree<x> {
  value: x;
  children: Array<ITree<x>>;