Skip to content

Instantly share code, notes, and snippets.

View dewey92's full-sized avatar
🌴

Jihad D. Waspada dewey92

🌴
View GitHub Profile
// pure :: Applicative f => a → f a
const pure = a => Functor.of(a)
// ap :: Applicative f => f (a → b) → f a → f b
const ap = (functor1, functor2) => functor1.ap(functor2)
// liftA :: Applicative f => (a → b) → f a → f b
const liftA = (fn, functor1) => functor1.map(fn)
// liftA2 :: Applicative f => (a → b → c) → f a → f b → f c
// filter :: (a → Bool) → [a] → [a]
const filter = fn => arr => arr.filter(fn)
// isEven :: Int → Bool
const isEven = num => num % 2 === 0
// oneToSix :: [Int]
const oneToSix = [1, 2, 3, 4, 5, 6]
// filterEvenNumbers :: [Int]
const filterEvenNumbers = filter(isEven)(oneToSix)
# [2, 4, 6]
// map :: (a → b) → [a] → [b]
const map = fn => arr => arr.map(fn)
// :: (Int → String) → [Int] → [String]
map(x => x.toString())([1, 2, 3])
# ['1', '2', '3']
// :: (Int → Int) → [Int] → [Int]
map(x => x + 1)([1, 2, 3])
// add :: Number → Number → Number
const add = (x, y) => x + y
// mathMsg :: (Number → Number → Number) → Number → Number → String
const mathMsg = (mathOp, x, y) => {
const result = mathOp(x, y)
return `The result of ${x} and ${y} is ${result}`
}
const jihad = liftA(getName, getChild(munirFam)) // Maybe('Jihad')
const pita = liftA(getName, getChild(wawanFam)) // Maybe('Puspita')
console.log(liftA2(textPenghulu, jihad, pita))
// => Maybe('Saya nikahkan Jihad dan Puspita, sah!')
const incr = x => x + 1
const add = curry((x, y)) => x + y
const sum3 = curry((x, y, z)) => x + y + z
const maybe1 = Maybe(1)
const maybe2 = Maybe(2)
const maybe3 = Maybe(3)
/* Pada dasarnya, liftA merupakan kombinasi dari map dan ap */
const getChild = person => Maybe(person.child)
const getName = person => person.name
const textPenghulu = curry((co, ce) => `Saya nikahkan ${co} dan ${ce}, sah!`)
const jihad = getName(getChild(mnunirFam))
const pita = getName(getChild(wawanFam))
console.log(textPenghulu(jihad, pita)
// Result: "Saya nikahkan undefined dan undefined, sah!"
// Expected: "Saya nikahkan Jihad dan Puspita, sah!"
/* Cara 1: dengan Higher Order Function */
const add = x => y => x + y
const add1 = add(1) // y => 1 + y
console.log(add1(3))
// => 4
/* Cara 2: pakai library biar gampang (Lodash, Ramda, etc) */
import { curry } from 'ramda'
const incr = x => x + 1
const add = curry((x, y) => x + y)
const sum3 = curry((x, y, z) => x + y + z)
liftA(incr, Functor1) === pure(incr).ap(Functor1)
liftA2(add, Functor1, Functor2) === pure(add).ap(Functor1).ap(Functor2)
liftA3(sum3, Functor1, Functor2, Functor3) === pure(sum3).ap(Functor1).ap(Functor2).ap(Functor3)
// form/utils.js
const createEitherFromConstraints = (obj, cons) => cons.reduce((acc, con) => acc.bind(con), Either.of(obj))
// module/auth/constraints.js
const checkUsername = auth => auth.username
? Right(auth)
: Left('No Username')
const checkPassword = auth => auth.password
? Right(auth)