// same thing: f(x)
const apply = (x, f) => f(x)
const touch = (f) => (x) => {
apply(x, f)
return x
}
// same thing: (f,g) => x => f(g(x))
const pipe =
(...xs) =>
(v) =>
xs.reduce(apply, v)
// same thing: Promise.resolve(1).then(f)
const map = (f) => (p) => p.then(f)
const tap = (f) => (p) => p.then(touch(f))
// same thing: Promise.reject(1).catch(f)
const mapE = (f) => (p) => p.catch(f)
const tapE = (f) => (p) => p.catch(touch(f))
// same thing: Promise.resolve(1).then(f).catch(() => d)
const mapWithDefault = (f, d) =>
pipe(
map(f),
mapE(() => d)
)
const github = {
user: (username) => `https://api.github.com/users/${username}`,
}
const responseJson = (r) => r.json()
// same thing
// const fetchUserByUsername = username => fetch(endpoints.user(username))
const fetchUserByUsername = pipe(
github.user,
fetch,
mapWithDefault(responseJson, null)
)
const getUser = pipe(
fetchUserByUsername,
tap(result => console.info(`What's [result]: `, {result})),
)
// getUser('username')
// Promise { ❓ }
You could be try and run this code with devTools (simply copy-paste) and call
getUser(CHANGEME)