Skip to content

Instantly share code, notes, and snippets.

View davidbarral's full-sized avatar

David Barral davidbarral

View GitHub Profile
@davidbarral
davidbarral / custom-promisify.js
Last active January 20, 2018 16:09
Promisify: node custom promisify
const { promisify } from "util";
const evenSuccess = (n, onSuccess, onError) => {
if (n % 2) {
onError(n);
} else {
onSuccess(n);
}
};
@davidbarral
davidbarral / promisify.js
Created January 20, 2018 16:11
Promisify: adhoc custom promisify
const CUSTOM = Symbol("promisify.custom");
const promisify = fn => {
if (fn[CUSTOM]) {
return fn[CUSTOM];
}
return (...args) => new Promise((resolve, reject) => {
fn(...args, (error, value) => {
if (error) {
@davidbarral
davidbarral / callbackify.js
Created January 20, 2018 16:12
Callbackify: node callbackify
const { callbackify } = require("util");
const evenSuccess = n => n % 2 ? Promise.reject("odd") : Promise.resolve("even");
callbackify(evenSuccess)(1, console.log); // "odd"
callbackify(evenSuccess)(2, console.log); // undefined "even"
@davidbarral
davidbarral / curry.js
Created February 11, 2018 15:57
Curry: partial application
const curry = fn => (...args) =>
args.length >= fn.length
? fn(...args)
: (...innerArgs) => fn(...args, ...innerArgs);
@davidbarral
davidbarral / curry.js
Created February 11, 2018 16:00
Curry: final version
const curry = fn => {
const curryN = (n, fn) => (...args) =>
args.length >= n
? fn(...args)
: curryN(n - args.length, (...innerArgs) => fn(...args, ...innerArgs));
return curryN(fn.length, fn);
};
@davidbarral
davidbarral / curry-test.js
Last active February 12, 2018 10:56
Curry: TDD partial application
const expect = x => ({
toBe: y => {
if (x !== y) {
throw new Error(`expected ${x} to be ${y}`);
}
}
});
const sum4 = curry((a, b, c, d) => a + b + c + d);
@davidbarral
davidbarral / curry.js
Created February 11, 2018 16:13
Curry: not working version
const curry = fn => (...args) =>
args.length >= fn.length
? fn(...args)
: curry((...innerArgs) => fn(...args, ...innerArgs));
@davidbarral
davidbarral / curry.js
Last active February 12, 2018 10:40
TDD: curry
expect(sum4(1)(2)(3,4)).toBe(10);
expect(sum4(1)(2)(3)(4)).toBe(10);
expect(sum4(1,2)(3)(4)).toBe(10);
@davidbarral
davidbarral / ramda-curry.js
Last active February 12, 2018 11:02
Curry: Ramda
import { curry, __ as _ } from "ramda";
const sum4 = curry((a, b, c, d) => a + b + c + d);
// Currying
sum4(1, 2, 3, 4);
sum4()(1, 2, 3, 4);
sum4(1)(2, 3, 4);
sum4(1)(2)(3, 4);
sum4(1)(2)(3)(4);
// Same as promise.js but with debug messages.
// Just run the code with node promise-debug.js.
// By setting DEBUG to true each promise will output in console some debug info
// There are 13 samples. In terms of debug output is better to focus in one of them at a time.
// You can do that by setting the FOCUS variable (i.e. FOCUS=11)
const DEBUG = false;
const FOCUS = false;
let promiseId = 1;