柯理化案例

  1. const _ = require("loadsh");
  2. // "".match(/\s+/g) 正则表达式 匹配字符串中的所有空格
  3. // "".match(/\d+/g) 这则表达式 匹配字符串中的所有数字
  4. // 封装一个匹配方法
  5. const matchNum = (reg, str) => str.match(reg);
  6. // 上面的方法 如果同一个正则使用多次,可以改造一下
  7. const curriedMatchNum = (reg) => {
  8. return (str) => str.match(reg);
  9. };
  10. const match1 = curriedMatchNum(/\d+/g);
  11. console.log(match1("xaskjl1d1"));
  12. console.log(match1("4 22"));
  13. // 使用curry
  14. const curryMatch = _.curry(function (reg, str) {
  15. return str.match(reg);
  16. });
  17. console.log(curryMatch(/\d+/g, "xaskjl1d1"));
  18. console.log(curryMatch(/\d+/g)("xaskjl1d1"));
  19. // 通过 curryMatch 函数来生成新的函数 判断字符串中是否含有数字
  20. const hasNumFn = (str) => {
  21. return curryMatch(/\d+/g)(str);
  22. };
  23. console.log("hasNumFn", hasNumFn("xxx"));
  24. console.log("hasNumFn", hasNumFn("xx2x2"));
  25. // 过滤一个数组中的所有含有数字的成员项
  26. const arr = ["2", "xxx", "22", 22, "ad", "5", 8, "xx1"];
  27. const filterNumFn = (array) => {
  28. const result = [];
  29. for (let val of array) {
  30. if (hasNumFn(`${val}`)) {
  31. result.push(val);
  32. }
  33. }
  34. return result;
  35. };
  36. console.log("filterNumFn", filterNumFn(arr));
  37. // 使用数组的filter方法,来过滤数组的数字成员项。并封装成一个柯理化函数
  38. const filterFn = _.curry(function (reg, array) {
  39. return array.filter((item) => `${item}`.match(reg));
  40. });
  41. console.log("filterFn", filterFn(/\d+/g)(arr));
  42. // 继续抽离
  43. const filterFn2 = _.curry(function (fn, array) {
  44. return array.filter(fn);
  45. });
  46. const filterNumber = filterFn2(function (item) {
  47. return `${item}`.match(/\d+/g);
  48. });
  49. console.log("filterNumber", filterNumber(arr));
  50. const filterNumber2 = filterFn2((item) => hasNumFn(`${item}`));
  51. console.log("filterNumber2", filterNumber2(arr));
  52. const filterNumber3 = filterFn2((item) => `${item}`.match(/\d+/g));
  53. console.log("filterNumber3", filterNumber3(arr));
  54. // 使用纯函数 柯理化的目的是为了更好的复用共用代码
  55. const matchSpace = (str) => `${str}`.match(/\s+/g);
  56. const hasSpaceCurry = _.curry((fn, arr) => arr.filter(fn));
  57. const hasSpace = hasSpaceCurry(matchSpace);
  58. console.log("hasSpace" , hasSpace(['x xx','2d d','222','x1']))
  59. console.log("hasSpace", hasSpace(["gg", "xd", "1 3", "11"]));
  60. // [ '1', '1' ]
  61. // [ '4', '22' ]
  62. // [ '1', '1' ]
  63. // [ '1', '1' ]
  64. // hasNumFn false
  65. // hasNumFn true
  66. // filterNumFn [ '2', '22', 22, '5', 8, 'xx1' ]
  67. // filterFn [ '2', '22', 22, '5', 8, 'xx1' ]
  68. // filterNumber [ '2', '22', 22, '5', 8, 'xx1' ]
  69. // filterNumber2 [ '2', '22', 22, '5', 8, 'xx1' ]
  70. // filterNumber3 [ '2', '22', 22, '5', 8, 'xx1' ]
  71. // hasSpace [("x xx", "2d d")];
  72. // hasSpace ["1 3"];