柯里化函数学习

柯里化:主要是为了把一个多参数(多元)函数转换成单参数(一元)函数,是函数式编程的一种概念。

特点:要求所有的参数被明确定义、当只有部分参数调用时,会返回一个新的函数,并等待外部其余参数。

用途:简化共用参数的传递,提高复用性

// 闭包函数 需要一个函数作为入参 并返回一个函数
function curry(fn) {
    return (fristArg)=> {
        return (secondArg)=> {
            return fn(fristArg, secondArg);
        }
    }
}


const curry = (fn) => {
    if (typeof fn !== 'function') {
        throw new Error(`${fn} is not a function`);
    }
    /**
     * 拼接参数
     * @private
     */
    const f= (...args1) => {
        // 当f函数调用传递参数比fn本身参数少 则直接执行fn 并将结果返回
        if (args1.length >= fn.length)
            return fn(...args1);
        // 当f函数调用传递参数比fn本身参数多 则需要拼接缓存参数
        return function t(...args2) {
            return f(...args1, ...args2);
        };
    };
    return f;
};
const add = (a, b) => {
    return a + b;
};
console.log(curry(add)(1)(2));

背景:面试题

给定一个函数

const add = (a: number, b: number) => {
	return a + b;
};

要求写一个函数fn, 通过fn(add)(1)(2)(3)(4)...方式调用。

/**
 *  相乘测试
 * @constructor
 */
const multiply = function (x: number, y: number) {
	return x * y;
};

/**
 * 参考柯里概念
 * @param add  必须是一个函数
 * @returns {temp}
 */
const CurrieFn = <Curry>(fn: curryParams, initialValue: any) => {
	let sum = initialValue;
	/**
	 * 定义一个函数,抛出去供下次传参调用
	 */
	const temp = <Curry>(x) => {
		sum = fn(sum, x);
		return temp;
	};
	/**
	 * 重写toString和valueOf方法
	 * 在参与计算、比较等涉及需要类型转换的时候(打印也会) 会调用toString或valueOf函数 输出结果
	 */
	temp.toString = temp.valueOf = function () {
		return sum;
	};
	return temp
};
const addNum = CurrieFn(add, 0)(1)(2)(3)(4);
console.log(addNum);
const MultiplyNum = CurrieFn(multiply, 1)(1)(2)(3)(4);
console.log(MultiplyNum);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值