Skip to content

Instantly share code, notes, and snippets.

View dewey92's full-sized avatar
🌴

Jihad D. Waspada dewey92

🌴
View GitHub Profile
// 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]
// 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
// getChild :: Person β†’ Maybe Person
const getChild = p => Maybe.of(p.child)
// getAge :: Person β†’ Maybe Number
const getAge = p => Maybe.of(p.age)
// safeDivisionBy :: Number β†’ Number β†’ Maybe Number
const safeDivisionBy = bawah => atas =>
(bawah === 0) ? Nothing() : Maybe.of(atas / bawah)
const getHalfOfChildsAge = compose(
safeDivisionBy(2),
getAge,
getChild
)
// getChild :: Person β†’ Maybe Person
// getAge :: Person β†’ Maybe Number
// safeDivisionBy :: Number β†’ Number β†’ Maybe Number
// composeK :: Monad m => ((y β†’ m z), (x β†’ m y), …, (a β†’ m b)) β†’ (a β†’ m z)
const composeK = (...fns) => init => {
if (!fns.length) throw new Error('Need at least 1 argument')
const lastArg = fns.pop();
return fns.reduceRight((acc, x) => acc.bind(x), lastArg(init))
}
@dewey92
dewey92 / EntryCodeChalange.md
Created February 23, 2018 14:31
Entry Challange

Write some application with messy code and file structures. This messy app

is:

  1. Inconsistent in naming convention
  2. Baking business logic into one big function
  3. Using quite a number of Imperative Programming styles
  4. ...

handle:

  1. Side effects (hitting API, sending email after registering, etc)
const AsyncState = {
idle: 'idle',
loading: 'loading',
loaded: 'loaded',
error: 'error'
}
const initialState = {
user: {
data: {},
@dewey92
dewey92 / commonReducer-2.js
Last active April 21, 2018 10:59
User with Post reducer
export default (state = initialState, action) => {
switch (action.type) {
case 'GET_USER_REQUEST':
return {
...state,
user: {
...state.user,
asyncState: AsyncState.loading
}
}
@dewey92
dewey92 / createAsyncAction.js
Last active April 22, 2018 10:29
Async Action Creators
const createAction = actionName => Object.assign(
payload => ({
type: actionName,
payload
}),
{ type: actionName } // <- Inject `type` attribute to the action func
)
const createAsyncAction = actionName => ({
request: createAction(actionName + '_REQUEST'),
// reducerHelper.js
export const createAsyncReducer = (initialState, asyncAction) =>
(state = initialState, action) => {
switch (action.type) {
case asyncAction.request.type:
return {
...state,
asyncState: AsyncState.loading
}
case asyncAction.success.type: