The basic concept

Okay, so the concept.

Partial Application function

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.

We can translate it into local applications

Turn a three-argument add function into an add3

Reference 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 + c fivePlus(4) // 9Copy the code

Curried – Functions

The transformation of a multi-parameter function into multiple single-parameter functions is to convert an n-yuan function into n unary 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
add2(10) // 12
Copy the code

Example 1: Split function to 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);Copy the code

Example 2: Vue3 CompositionAPI

The code for Antfu from Taiwan comes to mind

Antfu

Github.com/vueuse/vueu…

import { createApp, h, watchEffect, reactive } from "vue"; 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; };Copy the code

Above is an abstract Localstore hook

Const useStorage = (defaultValue) => {return useLocalStorage("store", defaultValue); }; const store = useStorage({count: 0})Copy the code

Let’s make fun of him with partial application functions

// Partial function const partial = (f,... args) => (... moreArgs) => f(... args, ... moreArgs); // Specify LocalStorage const useStorage = partial(useLocalStorage, "store"); // Declare partial(useStorage, {count: 0}) const store = partial(useStorage, {count: 0});Copy the code

Complete example

Github.com/su37josephx…

Example 3: React Hooks

Reacthook’s principle is no different, welcome to add

The interview guide

  • There is no

review

  • Closures are everywhere, but naming classic applications is a challenge. Saying Helloworld is no different from reciting.

\