Skip to content

Instantly share code, notes, and snippets.

@syzer
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syzer/a5ebde3031d76744397e to your computer and use it in GitHub Desktop.
Save syzer/a5ebde3031d76744397e to your computer and use it in GitHub Desktop.
Decorators are awesome
/**
* Created by syzer on 12/19/2014.
* ex shows how to decouple constant error checking from function/class body
* AKA TypeScript AKA WarnScript :)
*/
var _ = require('lodash');
function doStuffNumberPlusOneTimes(number, fun) {
"use strict";
// we want decouple this
if ('function'!== typeof fun) {
throw new TypeError('Must be function');
}
if ('print'=== fun.name) {
throw new Error('Cannot print');
}
if ('number' !== typeof number) {
throw new TypeError('Must be number');
}
// string number concat error here!
return _.times(number + 1, function (n) {
fun(n)
});
}
// comes from library
// curry unary combinators
function curry(fn) {
return function curried(a, optionalB) {
if (arguments.length > 1) {
return fn.call(this, a, optionalB);
} else {
return function partiallyApplied(b) {
return fn.call(this, a, b);
}
}
}
}
// comes from library
var before = curry(
function decorate(decoration, method) {
return function decoratedWithBefore() {
decoration.apply(this, arguments);
return method.apply(this, arguments);
};
}
);
///////////////////////////////////////lests start decoupling/////
// AKA class number with getters setters
// and a lot of boring autogenerated code
function fNum(number) {
if ('number' !== typeof number) {
throw new TypeError('Must be number');
}
return number;
}
function cannotPrint(fun) {
if ('function'!== typeof fun) {
throw new TypeError('Must be function');
}
if ('print'=== fun.name) {
throw new Error('Cannot print');
}
return fun;
}
var firstNum = before(function () {
fNum(arguments[0])
});
var secondCannotBePrint = before(function () {
cannotPrint(arguments[1]);
return arguments;
});
function doStuffNumberPlusOneTimes(number, otherParam) {
return _.times(number + 1, function (n) {
otherParam(n)
});
}
// js is awesome
//var doStuffNumberPlusOneTimes = firstNum(doStuffNumberPlusOneTimes);
var doStuffNumberPlusOneTimes = firstNum(secondCannotBePrint(doStuffNumberPlusOneTimes));
//doStuffNumberPlusOneTimes(5, console.log); // 6 times
// doStuffNumberPlusOneTimes('5', console.log); // 51 times
doStuffNumberPlusOneTimes(5, print); // cannot print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment