函数科里化

  • 在函数式编程中,科里化最重要的是把多参函数变为单参函数

  • 举个例子:我们创建一个通用函数来复用

 // 实现科里化
 Object.prototype.curry = function (func, ...args) {
      const that = this;
      // 得到从下标1开始的参数数组
      return function (...curArgs) {
        const totalArgs = [...args, ...curArgs];
        if (totalArgs.length >= func.length) {
          return func.apply(null, totalArgs);
        } else {
          totalArgs.unshift(func);
          return that.curry.apply(that, totalArgs)
        }
      }
    }
    const plugins = new Object();

    function createElement(container, name, props, styles, content) {
      const ele = document.createElement(name);
      container.appendChild(ele);
      for (let prop in props) {
        ele[prop] = props[prop]
      }
      for (let prop in styles) {
        ele.style[prop] = styles[prop];
      }
      content && (ele.innerHTML = content);
    }
    const div = document.querySelector('.container');
    // 使用科里化
    const createDiv = plugins.curry(createElement, div, 'div', {}, { width: '100px', height: '100px', border: '1px solid red' })
    createDiv('Hello1')
    createDiv('Hello2')
    createDiv('Hello3')
    createDiv('Hello4')
posted @ 2023-08-27 00:06  HuangBingQuan  阅读(3)  评论(0编辑  收藏  举报