Inspecting With Tap

Easily trace pipe and compose calls using tap(). (3 min. read)

One of pipe’s potential drawbacks is losing the ability to easily add code for debugging purposes.
Back when we had this
用水龙头检查 使用tap()轻松跟踪管道并编写调用
pipe的一个潜在缺点是无法轻松添加用于调试目的的代码。 当我们有这个的时候

  1. const doMath = (num) => {
  2. const doubled = num * 2;
  3. const tripled = doubled * 3;
  4. const squared = tripled * tripled;
  5. return squared + 1;
  6. }
  7. const result = doMath(2);
  8. console.log({ result });

干扰console.log或小黑客很容易。我们如何检查管道函数?

介绍水龙头。
它接受一个函数,通常是一个记录器,并向其提供当前值。
您可以在不影响管道的情况下做任何您想做的事情,
因为您只是在“敲打”管道!
:D

Jamming a console.log or little hack was easy. How do we inspect piped functions?
Introducing tap. It takes a function, usually a logger, and supplies it the current value. You can do whatever you want without affecting the pipeline since you’re just “tapping” it! :D

  1. import { pipe, tap } from 'ramda';
  2. const doMath = pipe(
  3. tap((num) => {
  4. console.log('initial number:', num);
  5. }),
  6. double,
  7. tap((num) => {
  8. console.log('after doubling:', num);
  9. }),
  10. triple,
  11. tap((num) => {
  12. console.log('after tripling:', num);
  13. }),
  14. square,
  15. tap((num) => {
  16. console.log('after squaring:', num);
  17. }),
  18. increment,
  19. tap((num) => {
  20. console.log('after incrementing:', num);
  21. }),
  22. );
  23. const result = doMath(2);
  24. console.log({ result });
  1. initial number: 2
  2. after doubling: 4
  3. after tripling: 12
  4. after squaring: 144
  5. after incrementing: 145
  6. { result: 145 }

您甚至不需要使用tap本身,只需插入一个返回其参数不变的函数即可。

  1. import { pipe, tap } from 'ramda';
  2. const doMath = pipe(
  3. (num) => {
  4. console.log('initial number:', num);
  5. return num;
  6. },
  7. double,
  8. (num) => {
  9. console.log('after doubling:', num);
  10. return num;
  11. },
  12. triple,
  13. (num) => {
  14. console.log('after tripling:', num);
  15. return num;
  16. },
  17. square,
  18. (num) => {
  19. console.log('after squaring:', num);
  20. return num;
  21. },
  22. increment,
  23. (num) => {
  24. console.log('after incrementing:', num);
  25. return num;
  26. }
  27. );
  28. const result = doMath(2);
  29. console.log({ result });
  1. initial number: 2
  2. after doubling: 4
  3. after tripling: 12
  4. after squaring: 144
  5. after incrementing: 145
  6. { result: 145 }

https://www.educative.io/courses/functional-programming-patterns-with-ramdajs/qVDzy5gG9B2