ECMAScript Pattern Matching (#tc39_study)

E0717cda3738e61e9b25188c6669a6c5?s=47 Yuki
October 09, 2019

ECMAScript Pattern Matching (#tc39_study)

E0717cda3738e61e9b25188c6669a6c5?s=128

Yuki

October 09, 2019
Tweet

Transcript

  1. ECMAScript Pattern Matching https:/ /github.com/tc39/proposal-pattern-matching @yukistch #tc39_study on Oct 9,

    2019 Presentation template by SlidesCarnival
  2. Outline • Github: https:/ /github.com/tc39/proposal-pattern-matching • Status: ◦ Stage: 1

    ◦ Author ▪ Kat Marchán (npm, @maybekatz) ◦ Champions ▪ Brian Terlson (Microsoft, @bterlson) ▪ Sebastian Markbåge (Facebook, @sebmarkbage) ▪ Kat Marchán (npm, @maybekatz) 2
  3. Summary • Introduction ◦ Pattern matching expression based on the

    existing Destructuring Binding Patterns. ◦ Draws heavily from corresponding features in Rust, F#, Scala, and Elixir/Erlang. • Implementations ◦ Babel Plugin ◦ Sweet.js macro ▪ NOTE: this isn't based on the proposal, this proposal is partially based on it! 3
  4. Motivating Examples (1/4) const res = await fetch(jsonService) case (res)

    { when {status: 200, headers: {'Content-Length': s}} -> console.log(`size is ${s}`), when {status: 404} -> console.log('JSON not found'), when {status} if (status >= 400) -> { throw new RequestError(res) }, } 4
  5. Motivating Examples (2/4) function todoApp (state = initialState, action) {

    return case (action) { when {type: 'set-visibility-filter', filter: visFilter} -> ({...state, visFilter}), when {type: 'add-todo', text} -> ({...state, todos: [...state.todos, {text}]}), when {type: 'toggle-todo', index} -> ( { ...state, todos: state.todos.map((todo, idx) => idx === index ? {...todo, done: !todo.done} : todo ) } ) when _ -> state // ignore unknown actions } } 5
  6. Motivating Examples (3/4) <Fetch url={API_URL}>{ props => case (props) {

    when {loading} -> <Loading /> when {error} -> <Error error={error} /> when {data} -> <Page data={data} /> } } </Fetch> 6
  7. Motivating Examples (4/4) const getLength = vector => case (vector)

    { when { x, y, z } -> Math.sqrt(x ** 2 + y ** 2 + z ** 2) when { x, y } -> Math.sqrt(x ** 2 + y ** 2) when [...etc] -> vector.length } getLength({x: 1, y: 2, z: 3}) // 3.74165 7
  8. Core Proposal: Overview "Pattern Matching for JavaScript" in the May

    2018 TC39 meeting
  9. References • Slide for May 2018 TC39 meeting • Core

    functionality ◦ https:/ /github.com/tc39/proposal-pattern-matching/blob /latest/CORE.md • Beyond This Spec ◦ https:/ /github.com/tc39/proposal-pattern-matching/blob /latest/TO_INFINITY_AND_BEYOND.md#catch-match • match->case ◦ https:/ /github.com/tc39/proposal-pattern-matching/pull /109 9