[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 ...
随机推荐
- Web登陆实例-—同步username
之前登陆学校的教务系统或者考试系统,进入界面都会有"欢迎***登陆本系统".当时就认为挺高级.如今轮 到自己做这个样例.突然感觉是so easy. 仅仅需简单几步,就可能够搞定. ...
- 如何在socket编程的Tcp连接中实现心跳协议
from http://blog.csdn.net/nyist327/article/details/39586203 心跳包的发送,通常有两种技术方法1:应用层自己实现的心跳包 由应用程序自己发送心 ...
- WinForm多语言版本实战项目演练
一.课程介绍 关于如何实现“WinForm多语言版本”网上有很多实现技术方案,可以说是“琳琅满目”,"包罗万象".俗话说的好:一千个读者就有一千个哈姆雷特!如果您工作中恰好也遇到这 ...
- delphi Image 处理
procedure ResizeBmp(Src,Dst:String);var SrcBM,DstBM:TBitMap; Rect:TRect; NewW,NewH,PicW,PicH:Integer ...
- [Asp.net mvc]Html.ValidationSummary(bool)
摘要 对ValidationSummary是HtmlHelper的扩展方法,用来返回 System.Web.Mvc.ModelStateDictionary (即ModelState)对象中的验证消息 ...
- 一步一步学习ASP.NET 5 (一)-基本概念和环境配置
编者语:时代在变,在csdn开博一年就发了那么的两篇文章.不管是什么原因都认为有愧了.可是今年重心都会在这里发表一些文章,和大家谈谈.NET, 移动跨平台,云计算等热门话题.希望有更好的交流. 好吧言 ...
- 提高你的代码稳定性与可读性-lint工具
from://http://wiki.eoe.cn/page/Improving_Your_Code_with_lint.html 负责人:lingzideshensha 分任务原文链接:http:/ ...
- codeforces Round #259(div2) C解题报告
C. Little Pony and Expected Maximum time limit per test 1 second memory limit per test 256 megabytes ...
- Java 集合系列Stack详细介绍(源码解析)和使用示例
Stack简介 Stack是栈.它的特性是:先进后出(FILO, First In Last Out). java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实现 ...
- 解决javamail ssl 测试unable to find valid certification path to requested target
运行 java InstallCert smtp.interdrp.com:465 得到jssecacerts文件后复制到jdk1.6.0_14\jre\lib\security目录 然后再发送邮件就 ...