Skip to content

Instantly share code, notes, and snippets.

@laser
laser / asset.rb
Last active January 4, 2016 03:59
blar.rb
module Prunable
def from_assets(assets)
assets.select &method(:is_prunable?)
end
def is_prunable?(asset)
asset.created_at < Date.today - 30
end
module_function from_assets, is_prunable?
@laser
laser / foo_spec_bug.rb
Last active January 4, 2016 03:19
foo.rb spec - with bug
require_relative '../foo'
describe StatefulCalculator do
before(:all) do
@subject = StatefulCalculator.new
end
it 'should add some numbers' do
expect(@subject.add(5).add(3).add(10).result).to eq(18)
end
@laser
laser / function_calc.rb
Last active January 4, 2016 00:39
Functional OO Calculator
class StatefulCalculator
def initialize(total)
@total = total
end
def add(x)
StatefulCalculator.new(@total + x)
end
def sub(x)
@laser
laser / higher_order_function.rb
Last active January 3, 2016 20:29
Higher-order function
# implemented in the controller action, result from the
# calculator operation is passed to the Repository
# app/controllers/calculation.rb
def create
h = ActiveSupport::JSON.decode(request.body)
fx = lambda do |op, mod, repo|
lambda do |x, y|
result = mod.method(op.to_sym).to_proc[x, y]
@laser
laser / _repository.rb
Last active January 3, 2016 19:49
Persisting Calculator
# a fake repository
class Repository
def self.save_calculation(op, n1, n2, result)
puts "just saved #{op}, #{n1}, #{n2}, #{result}"
end
end
@laser
laser / stateful_calc.rb
Last active January 3, 2016 19:48
Calculators
class StatefulCalculator
def initialize
@total = 0
end
def add(x)
@total += x
self
end
@laser
laser / stateful_calculator.rb
Last active January 3, 2016 17:09
Simple Calculators
class StatefulCalculator
def initialize
@total = 0
end
def add(x)
@total += x
self
end
@laser
laser / pure_fx_ruby.rb
Last active January 3, 2016 15:29
Pure functions in Ruby
class StatefulCalculator
def initialize
@total = 0
end
def add(x)
@total += x
self
end
@laser
laser / hash_fun.rb
Created January 17, 2014 16:16
Hash from array of name/value pairs with default value w/no mutation.
a = [["a", 1], ["b", 2]]
h = a.inject Hash.new(9999) do |hash, pair|
hash.merge Hash[[pair]]
end
h["a"] # 1
h["foo"] # 9999
@laser
laser / concurrent_sync.js
Last active June 10, 2016 23:56
Modifying "sync" to do parallel stuff
function sync(gen) {
var iterable, resume, check, vals, ops;
vals = [];
ops = 0;
check = function() {
if (vals.length == ops) {
if (ops == 1) {
iterable.next(vals[0]);