- const t = value = >{
- const fn = () = >value;
- fn.toString = () = >`t($ {
- value
- })`;
- return fn;
- };
-
- const someValue = t(2);
- console.log(someValue.toString() // "t(2)"
- );
- const assert = {
- same: (actual, expected, msg) => {
- if (actual.toString() !== expected.toString()) {
- throw new Error(`NOT OK: ${ msg }
- Expected: ${ expected }
- Actual: ${ actual }
- `);
- }
- console.log(`OK: ${ msg }`);
- }
- };
-
- {
- const msg = 'a value t(x) composed with t(0) ==== t(x)';
- const x = 20;
- const a = t(x)(t(0));
- const b = t(x);
- assert.same(a, b, msg);
- }
- {
- const msg = 'a value t(x) composed with t(1) ==== t(x + 1)';
- const x = 20;
- const a = t(x)(t(1));
- const b = t(x + 1);
- assert.same(a, b, msg);
- }
- NOT OK: a value t(x) composed with t(0) ==== t(x)
- Expected: t(20)
- Actual: 20
- const t = value => {
- const add = n => t(value + n);
- return Object.assign(add, {
- toString: () => `t(${ value })`,
- valueOf: () => value
- });
- };
- "OK: a value t(x) composed with t(0) ==== t(x)"
- "OK: a value t(x) composed with t(1) ==== t(x + 1)"
- // 自顶向下的函数组合:
- const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
- // 求和函数为 pipeline 传入需要的初始值
- // curry 化的 pipeline 复用度更好,我们可以延迟传入任意的初始值
- const sumT = (...fns) => pipe(...fns)(t(0));
- sumT(
- t(2),
- t(4),
- t(-1)
- ).valueOf(); // 5
- const result = compose(
- value1,
- value2,
- value3
- );
- .1 + .2 === .3 // false
- npm install--save moneysafe
- import { $ } from 'moneysafe';
- $(.1) + $(.2) === $(.3).cents; // true
- import { $ } from 'moneysafe';
- import { $$, subtractPercent, addPercent } from 'moneysafe/ledger';
- $$(
- $(40),
- $(60),
- // 减去折扣
- subtractPercent(20),
- // 上税
- addPercent(10)
- ).$; // 88
- git clone git@github.com: ericelliott / moneysafe.git
- npm install
- npm run watch
- rm source / moneysafe.js && touch source / moneysafe.js