Skip to content

Instantly share code, notes, and snippets.

@chvonrohr
Created November 10, 2019 11:50
Show Gist options
  • Save chvonrohr/deffaddb3cc56249f1a38a1ef18af106 to your computer and use it in GitHub Desktop.
Save chvonrohr/deffaddb3cc56249f1a38a1ef18af106 to your computer and use it in GitHub Desktop.
// helper functions
const compose = (...fns) => x => fns.reduceRight((res, fn) => fn(res), x);
const tap = f => x => { f(x); return x; };
const trace = label => tap(console.log.bind(console, label + ':'));
// container helpers
const isFunction = fn => fn && Object.prototype.toString.call(fn) === '[object Function]';
const isAsync = fn => fn && Object.prototype.toString.call(fn) === '[object AsyncFunction]';
const isPromise = p => p && Object.prototype.toString.call(p) === '[object Promise]';
class Container {
constructor(public value) {
//this.value = fn;
if (!isFunction(this.value) && !isAsync(this.value)) {
throw new TypeError(`Container expects a function, not a ${typeof this.value}.`);
};
}
run() {
return this.value();
}
map(fn) {
if (!isFunction(fn) && !isAsync(fn)) {
throw new TypeError(`The map method expects a function, not a ${typeof fn}.`);
};
return new Container(
() => isPromise(this.value()) ?
this.value().then(fn) : fn(this.value())
)
}
};
// code
const divideBy100 = num => num / 100;
const roundTo2dp = num => num.toFixed(2);
const addDollarSign = str => '$' + String(str);
const addSeparators = str => {
// add commas before the decimal point
str = str.replace(/(?<!\.\d+)\B(?=(\d{3})+\b)/g, `,`);
// add commas after the decimal point
str = str.replace(/(?<=\.(\d{3})+)\B/g, `,`);
return str;
};
const centsToDollars = compose(
addSeparators,
addDollarSign,
trace('before add dollar sign'),
roundTo2dp,
divideBy100,
);
console.log(centsToDollars(100000), '100000')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment