·  阅读 1780

# 📺 同步视频 一键三连

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.

``````// 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 + c
​
fivePlus(4) // 9

### 柯里化 -Curried functions

``````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

### 实例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

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;
};

``````// 用于指定持久化方案
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栈 一键三连