欢迎来到码农权的博客 MaNongGeGe.|

函数科里化

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

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

 // 实现科里化
 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')

本文作者:HuangBingQuan

本文链接:https://www.cnblogs.com/bingquan1/p/17659737.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   HuangBingQuan  阅读(9)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 不将就 码农权
  2. 2 Bleeding Love 码农权
  3. 3 想你念你 码农权
Bleeding Love - 码农权
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

Not available