2

I have some "dumb" question, sorry, but I really don't understand how it works.

In this createReducer call we are passing the second argument - js object (as I understand).

But I didn't see any key... only function. How it can works?

  export const todos = createReducer([], {
      [ActionTypes.ADD_TODO](state, action) {
        let text = action.text.trim()
        return [ ...state, text ]
      }
    })


function createReducer(initialState, handlers) {
  return function reducer(state = initialState, action) {
    if (handlers.hasOwnProperty(action.type)) {
      return handlers[action.type](state, action)
    } else {
      return state
    }
  }
}

I expected to see some like:

    {
          [ActionTypes.ADD_TODO] : (state, action) => {
                let text = action.text.trim()
                return [ ...state, text ]
              }
        }

The same with this construction: it's a function where is the key? How it can be?

const dynamicRoutes = {
    component : AppComponent,
    childRoutes : [
        {
            path : "/",
            getComponent(location, cb) {
                System.import("../modules/landing-page/LandingPage.module")
                    .then(loadRoute(cb))
                    .catch(errorLoading);
            }
        }

    ]
};

Thanks for any help!

Velidan
  • 5,526
  • 10
  • 48
  • 86

2 Answers2

2

It's a shorthand notation for methods. The key is the name of the function. So [ActionTypes.ADD_TODO](state, action) { is equivalent to [ActionTypes.ADD_TODO]: function(state, action) {

a better oliver
  • 26,330
  • 2
  • 58
  • 66
2

These are valid object initializer syntaxes. The second example is simple case of MethodDefinition (link to spec)

The case [ActionTypes.ADD_TODO](state, action) is also a MethodDefinition, but method/property name is defined as a ComputedPropertyName which has the syntax [ AssignmentExpression[In, ?Yield] ]. In case of ComputedPropertyNames it's possible to put a variable/object property between square brackets and the value will be used as property name in the newly created object.

Rafael
  • 18,349
  • 5
  • 58
  • 67