Skip to content

Instantly share code, notes, and snippets.

View IronSavior's full-sized avatar

Erik Elmore IronSavior

View GitHub Profile
@IronSavior
IronSavior / y_combinator.rb
Last active May 5, 2016 06:54
Obligatory Y combinator exercise
# Fixed point combinator. Because reasons.
# @param [Block with arity 1] Receives recursion Proc, must return Proc representing function (any arity)
# @return [Proc]
def Y
fail unless block_given?
lambda{ |fn| fn.call fn }.call lambda{ |fn|
lambda{ |*args|
(yield fn.call fn).call *args
}
}
@IronSavior
IronSavior / hashlike_fetch_cache.rb
Last active May 11, 2016 02:11
Fun with Hash-like objects
class HashlikeFetchCache
include HashlikeOverlay
def initialize( context )
@overlay = Hash[]
@context = context
freeze
end
def []( key )
class BaseEnum
include Enumerable
attr_reader :ctx
def initialize( *ctx )
@ctx = ctx
end
def each( *args, &blk )
return enum_for __callee__, *args unless block_given?
@IronSavior
IronSavior / tracing.rb
Created August 19, 2016 21:58
Minimalist program tracing with logger-like interface.
module Tracing
def trace_message( msg = yield )
level = String(__callee__).upcase
puts ' ** [%s] %s: %s' % [level, self.class, msg]
end
%i[debug info warn error].each{ |m| alias_method m, :trace_message }
end
@IronSavior
IronSavior / main.rs
Created October 7, 2016 07:04
Rust Hexdump
use std::io::{self, Read, BufRead};
use std::cmp;
use std::fmt::{self, Write};
const HR_BYTES_PER_LINE: usize = 16;
struct HexReader<T> {
inner: T,
buf: String,
buf_pos: usize,
require 'set'
# Invokes the block, passing in all or some of the input. If the block throws, the block will be invoked
# repeatedly for a progressively smaller subset of the batch until all elements are either processed or
# failed. Elements contained in sub-batches which succeed are never re-tried. Returns two Arrays, the first
# contains all items which succeeded and the second contains all elements which failed.
#
# This can be useful when a batch API will throw when it receies one or more malformed items, but doesn't
# tell you which input items were at fault.
#
@IronSavior
IronSavior / example-error.js
Last active February 19, 2022 10:18
Require AWS Lambda handler to invoke callback before exit (prevent Node exit until handler invokes callback)
const lambda_handler = require('lambda-handler');
exports.handler = lambda_handler(( event, ctx, done ) => {
// This will log a handled error to CloudWatch and return the error to AWS Lambda
throw 'BOOM!';
});
@IronSavior
IronSavior / to-function.js
Created August 7, 2017 22:30
JavaScript named predicate helper (Symbol#to_proc from Ruby)
"use strict";
// Make predicate funtions more convenient.
// Works like Ruby's Symbol#to_proc, which is usually called with the unary & operator and a Symbol literal:
// (ruby) %w[one two three].map(&:upcase) # returns ["ONE", "TWO", "THREE"]
// (js) ['one', 'two', 'three'].map(toFn('toUpperCase')); // returns ["ONE", "TWO", "THREE"]
// (js) ['one', 'two', 'three'].map(toFn`toUpperCase`); // same as above, but called via tagged string literal
// @param name {String} Name of method
// @param ...bound_args Arguments to bind NOTE: Args cannot be bound when calling as a tagged-template
// @return {Function} Function to call named method with bound args on any object given at time of invocation
module.exports = function toFn( name, ...bound_args ){
@IronSavior
IronSavior / error-policy-examples.js
Last active August 7, 2017 23:05
Composed error handling policy -- mix sync/async without missing errors
const error_policy = require('./error-policy');
// EventEmitter example
const {Readable} = require('stream');
class MyReadable extends Readable {
constructor(){
super(...arguments);
this.policy = error_policy(e => this.emit('error', e));
}
@IronSavior
IronSavior / concurrent-transform-stream.js
Last active September 18, 2017 19:59
A through2-compatible Transform stream which processes chunks with limited (or unlimited) concurrency
"use strict";
const {Transform} = require('readable-stream');
const PRIVATE = Symbol('ConcurrentTransform private state');
const NOOP_TRANSFORM = (chunk, _, done) => done(null, chunk);
const NOOP_FLUSH = done => done();
// Transform stream which processes chunks with limited (or unlimited) concurrency
class ConcurrentTransform extends Transform {
// @param opts {Object} Stream options. Set concurrency limit with "concurrent" (default concurrency: 1)
constructor( opts = {} ){