Last active
November 15, 2019 03:26
-
-
Save Offirmo/bacbb3aac7dbb3152584ac92db5f1360 to your computer and use it in GitHub Desktop.
Wrapping instead of currying
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
State, | |
set_age, | |
} from './state.ts' | |
const state: State = { ... } | |
// currying | |
const curried1_set_age = change_age.bind(null, state) // hard to read | |
curried1_set_age(42) // we are loosing the return value, so it's useless | |
// wrapping: much better: | |
// - more readable | |
// - can do more than just patching a param at the beginning or the end | |
const curried2_set_age = (age: Parameters<set_age>[1]) => { | |
state = set_age(state, age) | |
} | |
curried2_set_age(42) // global state was updated |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// modern code using immutable public data structures | |
// instead of outdated OOP ;) | |
export interface State { | |
name: string | |
age: number | |
} | |
export function set_age(state: Readonly<State>, age: number): Readonly<State> { | |
return { | |
...state, | |
age, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment