UNPKG

turbo-combine-reducers

Version:

Speed-optimized drop-in replacement for Redux's combineReducers

53 lines (42 loc) 1.35 kB
function combineReducers( reducers ) { var keys = Object.keys( reducers ), getNextState; getNextState = ( function() { var fn, i, key; fn = 'return {'; for ( i = 0; i < keys.length; i++ ) { // Rely on Quoted escaping of JSON.stringify with guarantee that // each member of Object.keys is a string. // // "If Type(value) is String, then return the result of calling the // abstract operation Quote with argument value. [...] The abstract // operation Quote(value) wraps a String value in double quotes and // escapes characters within it." // // https://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3 key = JSON.stringify( keys[ i ] ); fn += key + ':r[' + key + '](s[' + key + '],a),'; } fn += '}'; return new Function( 'r,s,a', fn ); } )(); return function combinedReducer( state, action ) { var nextState, i, key; // Assumed changed if initial state. if ( state === undefined ) { return getNextState( reducers, {}, action ); } nextState = getNextState( reducers, state, action ); // Determine whether state has changed. i = keys.length; while ( i-- ) { key = keys[ i ]; if ( state[ key ] !== nextState[ key ] ) { // Return immediately if a changed value is encountered. return nextState; } } return state; }; } module.exports = combineReducers;