Skip to content

Instantly share code, notes, and snippets.

View cameron-martin's full-sized avatar

Cameron Martin cameron-martin

View GitHub Profile
@cameron-martin
cameron-martin / gist:a7a91f0bc952e8a5c795
Last active August 29, 2015 14:02
Random Base-36 Benchmark
require 'benchmark'
n = 1_000_000
(1..50).step(5) do |length|
puts "Length: #{length}"
Benchmark.bm do |x|
x.report('array') { n.times { Array.new(length) { rand(36).to_s(36) }.join } }
# include from an initializer
module HstoreAccessor
def hstore_accessor(hstore_attribute, *keys)
Array(keys).flatten.each do |key|
define_method("#{key}=") do |value|
send("#{hstore_attribute}_will_change!")
send("#{hstore_attribute}=", (send(hstore_attribute) || {}).merge(key.to_s => value))
end
define_method(key) do
@cameron-martin
cameron-martin / gist:08abeaeae1bf746ef718
Last active August 29, 2015 14:05
Asynchronous vs synchronous
require 'eventmachine'
require 'benchmark'
rand_iterations = 10
define_method(:generate_func) do
# This is so we have n different function objects, which seems more realistic
proc { rand_iterations.times { rand(0..10) } }
end
require 'benchmark'
require 'ostruct'
n = 10_000
array = Array.new(1000) { |index| OpenStruct.new.tap { |struct| struct.price = index } };
Benchmark.bmbm do |x|
x.report('two stages') { n.times { array.map(&:price).inject(0, :+) } }
x.report('one stage') { n.times { array.inject(0) { |sum, product| sum += product.price } } }
@cameron-martin
cameron-martin / promise_pipelining.js
Last active September 26, 2015 17:30
Promise Pipelining
var pipeline = [
function(title) {
return Promise.resolve(title.replace(/P/g, 'p'));
},
function(title) {
return Promise.resolve(title.replace(/p/g, 't'));
}
];
function combinePipeline(pipeline) {
@cameron-martin
cameron-martin / README.md
Created July 24, 2019 11:52
Javascript CSS Preprocessor

Why?

Existing CSS preprocessors kinda suck:

  • Values cannot be easily shared between javascript and CSS, sometimes resulting in duplication
  • They're not suited to doing complicated computation. Want to do trigonometry in SASS? Not super easy. Moreover, writing
  • Modules don't exist for library code.

How?

@cameron-martin
cameron-martin / router-idea.ts
Last active July 24, 2019 11:56
A typesafe router sketch
interface RouteVariable<T> {
parse(value: string): { value: T, rest: string } | false;
}
const int: RouteVariable<number> = undefined as any;
const segment: RouteVariable<string> = undefined as any;
type RouteVariables<T> = { [K in keyof T]: RouteVariable<T[K]> };
type AddRoute<R> = <T extends any[]>(
import React, { useState, useMemo } from "react";
interface DataBinding<T> {
value: T;
setValue(value: T | ((prev: T) => T)): void;
}
/**
* Memoises the return value of a function based on the first argument by using a weakmap for the cache.
* @param f