[Functional Programming] Create Reusable Functions with Partial Application in JavaScript

本文介绍如何使用Curried函数实现部分应用,通过提前提供部分参数创建可重用的功能。以API请求为例,展示了如何通过Curried函数固定基地址,再根据不同需求提供其他参数,从而简化API调用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This lesson teaches you how arguments passed to a curried function allow us to store data in closure to be reused in our programs and applications. Since each argument, except for the final one, returns a new function, we can easily create reusable functions by supplying some of these arguments beforehand, and sharing these partially applied functions with other parts of our codebase. In this lesson, we'll create a curried function to fetch requests from an API that uses partial application to create reusable functionality.

Another way to do partially API call is using Proxy. Check this out.

// Partial Application

// Curried functions create a wonderful emergent property, "partial application",
// that is useful for building up reusability in our applications that you
// just can't get with normal, multivariate functions. Because curried functions
// return a new function with each argument (except for the final one), we are
// able to "partially apply" values and store them in closure, available to any
// subsequent function, thus creating new, reusable functions with some values
// already supplied.

// Imagine we have an application that needs to make requests to different APIs.
// We can create a function that bakes in the base URL, while allowing other
// arguments to be passed in later

const fetch = require('node-fetch')

const getFromAPI = baseURL => endPoint => callback =>
  fetch(`${baseURL}${endPoint}`)
    .then(res => res.json())
    .then(data => callback(data))
    .catch(err => {
      console.error(err.message)
    })

// Now we can partially apply a baseURL to create a reusable function for
// one of our APIs

const getGithub = getFromAPI(
  'https://api.github.com'
)

// We can create several get request functions by partially applying different
// endpoints to our getGithub function

const getGithubUsers = getGithub('/users')
const getGithubRepos = getGithub('/repositories')

// Now we can use our callback to get the data and do something with it.

getGithubUsers(data =>
  data.forEach(user => {
    console.log(`User: ${user.login}`)
  })
)
getGithubRepos(data =>
  data.forEach(repo => {
    console.log(`Repo: ${repo.name}`)
  })
)

// We can still continue to reuse previous partially applied functions

const getGithubOrgs = getGithub('/organizations')
getGithubOrgs(data =>
  data.forEach(org => {
    console.log(`Org: ${org.login}`)
  })
)

// We can start the process all over by partially applying a new baseURL

const getReddit = getFromAPI('https://reddit.com')

// And let's get some pictures of some cute animals

const getRedditAww = getReddit('/r/aww.json')

// And fetch the URLs of those images

const imageURLs = getRedditAww(payload =>
  payload.data.children.forEach(child => {
    console.log(
      child.data.preview.images[0].source.url
    )
  })
)

 

转载于:https://www.cnblogs.com/Answer1215/p/10585923.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值