每日一题12/16柯里化函数(闭包应用)

实现函数fn,让其具有如下功能(百度二面)

let res = fn(1,2)(3);
console.log(res); //=>6  1+2+3

这道题有两种思路,一个是利用console.log的特点,一个是利用闭包把变量保存下来。

const curring = () => {
    let arr = [];
    const add = (...params) => {
        // 把每一次执行ADD方法传递的值都保留下来
        arr = arr.concat(params);
        return add;
    };
    add.toString = () => {
        // 输出ADD会调用其toString方法
        return arr.reduce((total, item) => total + item);
    };
    return add;
};

let fn = curring();
let res = fn(1)(2)(3);
console.log(res); //->6

fn = curring();
res = fn(1, 2, 3)(4);
console.log(res); //->10

fn= curring();
res = fn(1)(2)(3)(4)(5);
console.log(res); //->15

关于console.log

console.log()输出原始值,但是也会调用tostring(),可以看到输出是 f ‘OK’,但是alert会直接调用tostring()输出字符串。

function fn() {}
fn.toString = function () {
    console.log('hhh我调用了tostring');
    return 'OK';
};
console.log(fn); //执行fn.toString
alert(fn); //->fn.toString

在这里插入图片描述
加了 alert之后的代码结果
在这里插入图片描述
点了确定之后。
在这里插入图片描述

利用闭包

//n用来记录执行次数
const curring = n => {
    let arr = [],
        index = 0;
    const add = (...params) => {
        index++;
        arr = arr.concat(params);
        if (index === n) {
            return arr.reduce((total, item) => total + item);
        }
        return add;
    };
    return add;
};

let fn= curring(3);
let res = fn(1)(2)(3);
console.log(res); //->6

fn= curring(2);
res = fn(1, 2, 3)(4);
console.log(res); //->10

fn = curring(5);//执行次数n必须和fn执行次数一致
res = fn(1)(2)(3)(4)(5);
console.log(res); //->15

柯里化函数 curring():预先处理的思想「利用闭包,保存私有上下文中的一些信息,供其下级上下文中调取使用,也就是我们把一些信息先预先保存下来,后期让其下级上下文使用」 => 大函数执行返回小函数。
还有一个compose函数,也是非常有意思的,curring函数和compose函数都可以增加代码可读性,接下来的每日一题就要讲compose函数了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值