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