[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 ...
随机推荐
- SGU 200. Cracking RSA (高斯消元求自由变元个数)
题目链接:http://acm.sgu.ru/problem.php?contest=0&problem=200 200. Cracking RSA time limit per test: ...
- 【Java】须要配置的三个Java环境变量
我的电脑→属性→高级系统设置→高级→环境变量 1.JAVA_HOME : JDK的安装路径 2.PATH : %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin; 3.CLASSP ...
- Programmed Adjustable Power
Programmed Adjustable Power I just explored an easy scheme to design a high precision programmed adj ...
- linux 内核升级2 转
linux内核升级 一.Linux内核概览 Linux是一个一体化内核(monolithic kernel)系统. 设备驱动程序可以完全访问硬件. Linux内的设备驱动程序可以方便地以模块化(mod ...
- Java对象池
单例模式是限制了一个类只能有一个实例,对象池模式则是限制一个类实例的个数.对象池类就像是一个对象管理员,它以Static列表(也就是装对象的池子)的形式存存储某个实例数受限的类的实例,每一个实例还要加 ...
- Spring Boot开发之流水无情(二)
http://my.oschina.net/u/1027043/blog/406558 上篇散仙写了一个很简单的入门级的Spring Boot的例子,没啥技术含量,不过,其实学任何东西只要找到第一个突 ...
- rtorrent - 强大的命令行BT客户端
NOTE - 文中展示的所有示例和指令都已经在Ubuntu 13.04中测试过. 一. 安装 [root@GY-10000 data]# yum search rtorrent ...
- 创建、修改、删除ORACLE表空间
//创建表空间 create tablespace MyFirstSpace datafile '/opt/oracle/app/oracle/product/9.2.0/dbs/MyFirstSpa ...
- ExtJS学习-----------Ext.Array,ExtJS对javascript中的Array的扩展(实例)
(1)clean var arr = [1,2,null,3,'']; alert(Ext.Array.clean(arr)); //clean的对象:(value === null) || (val ...
- Robotframework(3):使用pycharm编写和运行RF脚本
转自:http://blog.csdn.net/ccggaag/article/details/77529724 我们在使用Robotframework时,经常编写脚本的人或许会不习惯,不过没关系!我 ...