Day10-闭包应用-偏应用函数与柯里化

3,270 阅读4分钟

📺 同步视频 一键三连

www.bilibili.com/video/BV1gr…

365天打卡记录

🔥 创作不易、大家帮然叔 B栈 一键三连

基本概念

好先介绍概念。

偏应用函数 Partial application

In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity.

我们可以把他翻译成局部应用

将一个三参数的add函数变为一个add3

参考 github.com/hemanth/fun…

// Helper to create partially applied functions
// Takes a function and some arguments
const partial = (f, ...args) =>
  // returns a function that takes the rest of the arguments
  (...moreArgs) =>
    // and calls the original function with all of them
    f(...args, ...moreArgs)
​
// Something to apply
const add3 = (a, b, c) => a + b + c
​
// Partially applying `2` and `3` to `add3` gives you a one-argument function
const fivePlus = partial(add3, 2, 3) // (c) => 2 + 3 + cfivePlus(4) // 9

柯里化 -Curried functions

柯里化是将一个多参数函数转换成多个单参数函数,也就是将一个 n 元函数转换成 n 个一元函数

const sum = (a, b) => a + b
const curriedSum = (a) => (b) => a + b
const curry = fn => x => y => fn(x , y)
curriedSum(40)(2) // 42.
const add2 = curriedSum(2) // (b) => 2 + b
add2(10) // 12

实例1: 分割函数转CSV

const split = (regex, str) => ("" + str).split(regex);
const elements = split("v1,v2,v3", /,\s*/);
const partial =
  (f, ...args) =>
  (...moreArgs) =>
    f(...args, ...moreArgs);
const csv = partial(split, /,\s*/);
const s = csv("v1,v2,v3");
console.log(s);

实例2: Vue3 CompositionAPI

想起了来自台湾的Antfu的代码

Antfu image-20220110184054522

github.com/vueuse/vueu…

import { createApp, h, watchEffect, reactive } from "vue";
// 抽象的LocalStorage解决方案
const useLocalStorage = (key, defaultValue) => {
  const data = reactive({});
  Object.assign(
    data,
    (localStorage[key] && JSON.parse(localStorage[key])) || defaultValue
  );
  watchEffect(() => (localStorage[key] = JSON.stringify(data)));
  return data;
};

上面是一个抽象Localstore钩子

// 用于指定持久化方案
const useStorage = (defaultValue) => {
  return useLocalStorage("store", defaultValue);
};
const store = useStorage({count: 0})

下面我们用偏应用函数恶搞一下他

// 偏应用函数
const partial =
(f, ...args) =>
(...moreArgs) =>
f(...args, ...moreArgs);
​
// 指定使用LocalStorage存储
const useStorage = partial(useLocalStorage, "store");
// 声明响应式数据
const store = partial(useStorage, { count: 0 });

完整的例子

github.com/su37josephx…

实例3: React Hooks

reacthook原理没有区别,欢迎大家补充

面试攻略

点评

  • 闭包处处都有,但是能说出经典应用又是一个难题。说Helloworld和背题没啥区别。

365天打卡记录

🔥 创作不易、大家帮然叔 B栈 一键三连