[Functional Programming] Create Reusable Functions with Partial Application in JavaScript
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[].source.url
)
})
)
[Functional Programming] Create Reusable Functions with Partial Application in JavaScript的更多相关文章
- [Functional Programming] From simple implementation to Currying to Partial Application
Let's say we want to write a most simple implementation 'avg' function: const avg = list => { let ...
- [Functional Programming] Running though a serial number prediction functions for tagging, pairing the result into object
Let's we have some prediction functions, for each prediction function has a corresponding tag: const ...
- Functional Programming without Lambda - Part 1 Functional Composition
Functions in Java Prior to the introduction of Lambda Expressions feature in version 8, Java had lon ...
- a primary example for Functional programming in javascript
background In pursuit of a real-world application, let’s say we need an e-commerce web applicationfo ...
- Functional programming
In computer science, functional programming is a programming paradigm, a style of building the struc ...
- Currying vs Partial Application
柯里化相当于函数重构: 偏函数相当于函数适配. So, what is the difference between currying and partial application? As we s ...
- Monad (functional programming)
In functional programming, a monad is a design pattern that defines how functions, actions, inputs, ...
- Beginning Scala study note(4) Functional Programming in Scala
1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...
- Functional Programming without Lambda - Part 2 Lifting, Functor, Monad
Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...
随机推荐
- STM32的CRC32 测试代码
// STM32 CRC32 Test App - sourcer32@gmail.com #include <windows.h> #include <stdio.h> DW ...
- vue首屏加载优化
库使用情况 vue vue-router axios muse-ui material-icons vue-baidu-map 未优化前 首先我们在正常情况下build 优化 1. 按需加载 当前流行 ...
- Vue 插件写法
都说Vue2简单,上手容易,但小马过河,自己试了才晓得,除了ES6语法和webpack的配置让你感到陌生,重要的是思路的变换,以前随便拿全局变量和修改dom的锤子不能用了,变换到关注数据本身.vue的 ...
- 在Brackets中使用Emmet
当在Brackets中安装上Emmet插件后,就可以使用Emmet的语法来加速前端编写. 有关html ● 子关系> div>ul>li ● 相邻+ div+p+bq ● 上一级^ ...
- Visual Studio 2013 sqlce 配置(转)
Visual Studio 2013 把內建 SQL CE 的管理工具拿掉了 下载SQL Server Compact Toolbox by ErikEJ并安装 打开VS2013,新建一工程,在“视图 ...
- SpringUtils
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationConte ...
- Cocos2d-x开源、跨平台的游戏引擎
from://http://blog.linguofeng.com/pages/language/c/Cocos2dx.html Cocos2d-x 开源.跨平台的游戏引擎 一.下载 http://c ...
- Activity间用Intent、Bundle、onActivityResult进行传值
其实Activity间的传值就是通过Bundle,intent中也是自动生成了Bundle来传值,里面还有个onActivityResult()方法也可以传送数值. 如果一个Activity是由sta ...
- 使用jstl标签时提示The absolute uri: http://java.sun.com/jsp/jstl/core cannot
http://www.360doc.com/content/11/1219/15/1007797_173395882.shtml 检查应用目录下WEB-INF的lib里是否有jstl.jar和stan ...
- BMap:WEB 服务API
ylbtech-Map-Baidu: WEB 服务API 百度地图Web服务API为开发者提供http/https接口,即开发者通过http/https形式发起检索请求,获取返回json或xml格式的 ...