Skip to content

Instantly share code, notes, and snippets.

View WaldoJeffers's full-sized avatar
🤓
Building a new standard JS library: conductor

WaldoJeffers

🤓
Building a new standard JS library: conductor
View GitHub Profile
const fetchJSON = url => fetch(url).then(res => res.json())
const fetchCharacter = id => fetchJSON(`https://swapi.co/api/people/${id}`)
// fetchCharacter(1) == { name: 'Luke Skywalker', homeworld: 'https://swapi.co/api/planets/1/' }
const character_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import { compose, get } from 'conductor'
const getHomeworldName = compose(get('name'), fetchJSON, get('homeworld'), fetchCharacter)
// getHomeworldName(1) == { name: 'Tatooine', ... }
const toObj = (key, value) => ({ [key]: value }) // toObj('hello', 'world) === { hello: 'world' }
const countOne = name => toObj(name, 1) // countOne('Tatooine') === { Tatooine: 1 }
import { compose } from 'conductor'
const countHomeworld = compose(countOne, getHomeworldName)
// countHomeworld(1) == { Tatooine: 1 }
import { add, mergeWith } from 'conductor'
const mergeByAdding = mergeWith(add)
// mergeByAdding({ Alderaan: 1, Tattooine: 2 }, { Tattooine: 1 })
// == { Alderaan: 1, Tattooine: 3 }
const reducer = (acc, character_id) => getHomeworldName(character_id)
.then(mergeByAdding(acc))
// reducer({ Tatooine: 1 }, 3) == { Naboo: 1, Tatooine: 1 }
import { reduce } from 'conductor'
const homeworld_stats = reduce(reducer, character_ids)
// { Alderaan: 1, Naboo: 1, Stewjon: 1, Tatooine: 7 }
import { map } from 'conductor'
const character_ids = [1, 2, 3, 4, 5]
const fetchCharacter = id => fetch(`https://swapi.co/api/people/${id}`).then(res => res.json())
await map(fetchCharacter, characters_ids) // [{ name: 'Luke Skywalker }, { name: 'C-3PO' }, ...]
import { compose, equals, filter, get } from 'conductor'
const character_ids = [1, 2, 3, 4, 5]
const fetchCharacter = id => fetch(`https://swapi.co/api/people/${id}`).then(res => res.json())
const hasBlueEyes = compose(equals('blue'), get('eye_color'), fetchCharacter))
await filter(hasBlueEyes, characters_ids) // [{ name: 'Luke Skywalker }, { name: 'Owen Lars' }, ...]