GithubHelp home page GithubHelp logo

proposal-pattern-matching's Introduction

ECMAScript 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)

Introduction

This proposal adds a pattern matching expression to the language, based on the existing Destructuring Binding Patterns.

There's many proposals potentially related to this one, and other proposals might mention interaction with this. This file includes casual, example-based discussion of the proposal, and there's also a document describing the core semantics in more formal language, which will be iterated over into the final Spec-ese.

There's also a document including suggestions for other future proposals, which are dependent on this one, but do not directly affect the main behavior of the feature.

This proposal was approved for Stage 1 in the May 2018 TC39 meeting, and slides for that presentation are available.

This proposal draws heavily from corresponding features in Rust, F#, Scala, and Elixir/Erlang.

Motivating Examples

Matching fetch() responses:

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)
  }
}

Terser, more functional handling of Redux reducers. Compare with this same example in the Redux documentation:

function todoApp (state = initialState, action) {
  case (action) {
    when {type: 'set-visibility-filter', filter: visFilter} ->
      return {...state, visFilter}
    when {type: 'add-todo', text} ->
      return {...state, todos: [...state.todos, {text}]}
    when {type: 'toggle-todo', index} -> {
      return {
        ...state,
        todos: state.todos.map((todo, idx) => idx === index
          ? {...todo, done: !todo.done}
          : todo
        )
      }
    }
    when {} -> {} // ignore unknown actions
  }
}

Or mixed in with JSX code for quick props handling, assuming implicit do:

<Fetch url={API_URL}>{
  props => case (props) {
    when {loading} -> <Loading />
    when {error} -> <Error error={error} />
    when {data} -> <Page data={data} />
    when _ -> throw new Error('badmatch')
  }
}
</Fetch>

(via Divjot Singh)

General structural duck-typing on an API for vector-likes.

const getLength = vector => {
  case (vector) {
    when { x, y, z } ->
      return Math.sqrt(x ** 2 + y ** 2 + z ** 2)
    when { x, y } ->
      return Math.sqrt(x ** 2 + y ** 2)
    when [...etc] ->
      return vector.length
  }
}
getLength({x: 1, y: 2, z: 3}) // 3.74165

Implementations

proposal-pattern-matching's People

Contributors

bterlson avatar coderitual avatar dotproto avatar erikras avatar fregante avatar geoffreydhuyvetters avatar indierojo avatar jonathansampson avatar kimroen avatar legodude17 avatar ljharb avatar rattrayalex avatar tabatkins avatar vitapluvia avatar zkat avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.