Photo by charlesdeluvio on Unsplash
And You're Teaching It Wrong!!
Alex Riviere
Senior Frontend Web Developer
blog: alex.party
mastodon: @fimion@notacult.social
bsky: @dangitalex.wtf
Currying Functions are just
Scope Closures
function addThree(a){
return function(b){
return function(c){
return a+b+c;
}
}
}
addThree(1)(2)(3); // result: 6
Photo by Tom Dillon on Unsplash
function addThree(a){
return function(b){
return function(c){
return a+b+c;
}
}
}
addThree(1)(2)(3);
A function that returns an object without having to define the type of that object.
When a function that is defined inside of a parent function is exposed outside of it's original scope, it has access to the inner scope of the original parent function.
export const authFetchStuffFactory = (token) =>{
const fetchStuffFactory = (url) =>{
const fetchStuff = (options = {})=>{
options.headers = {
...(options.headers||{}),
'Authorization':`Bearer ${token}`
};
return fetch(url, options);
};
return fetchStuff;
};
return fetchStuffFactory;
};
import {authFetchStuffFactory} from './my-library.js';
const token = 'my-very-secret-token';
const endpoint = '/api/my-secure-endpoint'
await authFetchStuffFactory(token)(endpoint)();
// file: ./auth-fetch.js
import {authFetchStuffFactory} from './my-library.js';
import {getToken} from './auth-provider.js';
const authFetchFactory = authFetchStuffFactory(getToken());
export const fetchUsers = authFetchFactory('/api/users');
export const fetchReports = authFetchFactory('/api/reports');
// file: my-component.jsx
import {fetchUsers} from './auth-fetch.js';
// ... somewhere in our component...
await fetchUsers();
Alex Riviere
Senior Frontend Web Developer
blog: alex.party
mastodon: @fimion@notacult.social
bsky: @dangitalex.wtf
Slides available at:
https://slides.com/fimion/currying-thunderplains-2023