function objectSetImmutableJs() { var obj = seamlessImmutableJs.from({ value : Math.random() }); for(var i = 0; i < REPEATS; i++) { obj.set('value', Math.random()); } }
function objectGetSeamlessImmutableJs() { var obj = seamlessImmutableJs.from({ value : Math.random() }); var value; for(var i = 0; i < REPEATS; i++) { value = obj.value; } }
function arraySetInSeamlessImmutableJs() { var arr = seamlessImmutableJs.from([[ Math.random(), Math.random(), Math.random(), Math.random(), Math.random() ]]); var maxIndex = arr[0].length - 1; for(var i = 0; i < REPEATS; i++) { arr = arr.setIn([0, ~~(Math.random() * maxIndex)], Math.random()); } }
function arrayGetSeamlessImmutableJs() { var arr = seamlessImmutableJs.from([ Math.random(), Math.random(), Math.random(), Math.random(), Math.random() ]); var value; var maxIndex = arr.length - 1; for(var i = 0; i < REPEATS; i++) { value = arr[~~(Math.random() * maxIndex)]; } }
function objectSetInSeamlessImmutableJs() { var obj = seamlessImmutableJs.from({ data : { value : Math.random() } }); for(var i = 0; i < REPEATS; i++) { obj = obj.setIn(['data', 'value'], Math.random()); } }
it("should only notify listeners once for history changes", () => { const testStore = new SlidesStore(new FileStore()); // Set initial state testStore.history = Immutable.from([{ slides: ["a"] }]); testStore.historyIndex = 0; const historaySpy = spy(); const historayIndexSpy = spy(); // Autorun invokes the callback immediatly and adds listeners // for all observables in the callback scope. const disposer = autorun(() => { historaySpy(testStore.history); historayIndexSpy(testStore.historyIndex); }); // Verify that autorun invoked the spy once on initialization expect(historaySpy.callCount).to.equal(1); expect(historayIndexSpy.callCount).to.equal(1); // Verify that autorun was called with the initial values // args[0][0] gets the first call then the first entry in arguments array. expect(historaySpy.args[0][0]).to.eql(Immutable.from([{ slides: ["a"] }])); expect(historayIndexSpy.args[0][0]).to.eql(0); // Call our function that should trigger autorun testStore._addToHistory({ slides: ["b"] }); // Verify that transaction only reran autorun once. expect(historaySpy.callCount).to.equal(2); expect(historayIndexSpy.callCount).to.equal(2); // Verify the values passed to autorun were the expected values // args[1][0] gets the second call then the first entry in arguments array. expect(historaySpy.args[1][0]).to.eql(Immutable.from([{ slides: ["a"] }, { slides: ["b"] }])); expect(historayIndexSpy.args[1][0]).to.eql(1); // Remove autorun. This belongs in an after/afterEach statement. disposer(); });
(value, newEntity) => { let newValue = value; if (!newValue) { newValue = Immutable.from({}); } return newValue.merge( { ...newEntity, [entitySchema.idFieldName]: entityId, } ); },
// General Operation generateUUID({reqId, entry}) { const genUUID = { [this.uuidField]: `${this.uuidPrefix}${uuid.v4()}`}; let generatedEntry; if (entry) { generatedEntry = Immutable.from(entry).merge(genUUID); } else { generatedEntry = genUUID; } return this.dbExist({ reqId, id: generatedEntry }).then((exist) => { if (exist) { return this.generateUUID({ reqId }); } return generatedEntry; }); }
constructor() { const initialState = Immutable.from({}); this.store = createStore( reducers, initialState, composeWithDevTools(applyMiddleware(thunk)) ); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers').default; this.store.replaceReducer(nextRootReducer); }); } }
/** * Apply conditions (and extensions) to the cells of a view * * @export * @param {BunsenView} view View to process * @param {any} value The value we want to check conditions against * @returns {BunsenView} View after conditions have been applied */ export default function evaluateView (view, value) { const wrappedValue = new ValueWrapper(value, []) const immutableView = Immutable.from(view) if (view.cells === undefined) { return view } try { // Make sure we preserve non-array value so we get useful validation errors const cells = !Array.isArray(view.cells) ? view.cells : _.chain(view.cells) .map(checkRootCells(immutableView, wrappedValue)) .filter(isNotUndefined) .value() return Object.assign(_.clone(view), { cells }) } catch (e) { // Unfortunately this is necessary because view validation happens outside of the reducer, // so we have no guarantee that the view is valid and it may cause run time errors. Returning return view } }
function setStatusWithDefaults(state, collectionName, entityId, getNewStatus) { return state.updateIn( ['statuses', collectionName, entityId], (currentStatus) => _.merge({}, defaultStatus, currentStatus, getNewStatus(currentStatus)) ); } export default createReducer( t.struct({ collections: NormalizedEntityDictionary, statuses: t.dict(CollectionName, t.dict(EntityId, t.maybe(EntityStatus))), errors: t.dict(CollectionName, t.dict(EntityId, t.maybe(t.Object))), }), Immutable.from({ collections: {}, statuses: {}, errors: {}, }), { [ENSURE_ENTITY]: [ t.struct({ collectionName: t.String, entityId: EntityId, }), (state, action) => { const { collectionName, entityId } = action.payload; return setStatusWithDefaults(state, collectionName, entityId, (currentStatus) => ({ transient: currentStatus ? currentStatus.transient : true, })); }, ],
CHANGE_LAYOUT: (state, action) => state.set('gridLayout', Immutable.from(action.payload)),
deserialize: (serializedData) => Immutable.from(JSON.parse(serializedData)),
import { handleActions } from 'redux-actions'; import Immutable from 'seamless-immutable'; const initialState = Immutable.from([]); export default handleActions({ PORT_RESP: (state, { payload }) => Immutable.from(payload), }, initialState);
export type AppState = { activeTab: number; editors: Array<TabState>; macroSettingsEditorState: EditorState; macroSettingsOpen: boolean; macros: MacroList; patientSettingsOpen: boolean; }; // create saga middleware const sagaMiddleware = createSagaMiddleware(); const initialState: Immutable<AppState> = I.from({ activeTab: 0, editors: [], macroSettingsEditorState: EditorState.createEmpty(), macroSettingsOpen: false, macros, patientSettingsOpen: false, }); const store = createStore( reducer, initialState, applyMiddleware(sagaMiddleware) ); // then run the saga sagaMiddleware.run(rootSaga); export default store;
import { INITIALIZE, INITIALIZE_FINISH, LOGIN, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_SUCCESS, LOGOUT_FAILURE, } from './actions'; export default createReducer( AuthContext, Immutable.from({ user: null, error: null, initializing: false, initialized: false, authenticating: false, }), { [INITIALIZE]: (state, action) => { return state.merge({ ...action.payload, initializing: true, }); }, [INITIALIZE_FINISH]: (state, action) => { return state.merge({ ...action.payload, initializing: false, initialized: true,
import { handleActions } from 'redux-actions'; import Immutable from 'seamless-immutable'; const initialState = Immutable.from({ coreURL: '', controllerURL: '', controllerName: '', }); export default handleActions({ SETTING_CONTROLLER: (state, { payload }) => state.merge(payload), SETTING_CONTROLLER_RESP: (state) => state, }, initialState);
return function (cell) { return checkCell(view, value, Immutable.from(cell)).asMutable() }
export default function routerReducer(navigationState=initialState,action){ if(!Immutable.isImmutable(navigationState)){ navigationState = Immutable.from(navigationState) } let scene,path,nextScene path = resolvePath(navigationState) if(action.type === constants.PUSH_SCENE){ scene = locateScene(action.scenes,action.key) if(!scene){ return navigationState } nextScene = scene //initialize tabbar scene state if(scene.tabbar){ nextScene = scene.set("routes",scene.routes.map((item,i)=>{ return { index:0, ...item, routes:[item.routes[0]] } })).set("index",0) } if(navigationState.routes.length === 0){ navigationState = navigationState.setIn(["routes",0],nextScene) return navigationState } } if(action.type === constants.POP_SCENE){ nextScene = getInPath(navigationState,path).routes.slice(-2,-1)[0] } //toggle tabbar visible if(path.length > 2 && (action.type === constants.POP_SCENE || action.type === constants.PUSH_SCENE)){ const tabbarPath = path.slice(0,-2) const tabbarScene = getInPath(navigationState,tabbarPath) if(tabbarScene){ navigationState = navigationState.updateIn(tabbarPath, tabbarState=>tabbarState.set("visible",typeof nextScene.hideTabBar === "boolean"?!nextScene.hideTabBar:true) ) } } //switch scene between tabs if(action.type === constants.FOCUS_SCENE){ return focusScene(navigationState,action.key) } function nestReducer(navState,navAction,scenePath){ return scenePath.length > 0?navState.updateIn(scenePath,nestNavState=>navigationReducer(nestNavState,navAction)): navigationReducer(navState,navAction) } switch(action.type){ case constants.PUSH_SCENE: const injectedAction = { type:action.type, state:{ params:action.params, ...nextScene, key:action.key } } navigationState = nestReducer(navigationState,injectedAction,path) break case constants.POP_SCENE: case constants.JUMPTO_SCENE: case constants.RELOAD_SCENE: navigationState = nestReducer(navigationState,action,path) break case constants.RESET_SCENE: navigationState = navigationReducer(navigationState,action) break } return navigationState }
PORT_RESP: (state, { payload }) => Immutable.from(payload),
import { combineReducers } from 'redux'; import { LOCATION_CHANGE } from 'react-router-redux'; import { reducer as toastr } from 'react-redux-toastr'; import Immutable from 'seamless-immutable'; import topology from './Topology'; import controllerStatus from './ControllerStatus'; import flowtable from './Flowtable'; import layout from './Layout'; import setting from './Setting'; import portStatus from './PortStatus'; const routeInitialState = Immutable.from({ locationBeforeTransitions: null, }); const routing = (state = routeInitialState, action) => { if (action.type === LOCATION_CHANGE) { return { ...state, locationBeforeTransitions: action.payload, }; } return state; }; export default combineReducers({ toastr, routing, layout, topology, controllerStatus,
import { handleActions } from 'redux-actions'; import Immutable from 'seamless-immutable'; const initialState = Immutable.from({ gridLayout: [ { i: 'Flowtable', x: 1, y: 5, w: 8, h: 7 }, { i: 'ControllerStatus', x: 4, y: 0, w: 5, h: 3 }, { i: 'PortStatus', x: 4, y: 0, w: 5, h: 3 }, { i: 'SettingContainer', x: 1, y: 0, w: 6, h: 8 }, ], hiddenPanel: [], maximumPanel: '', }); export default handleActions({ CHANGE_LAYOUT: (state, action) => state.set('gridLayout', Immutable.from(action.payload)), TOGGLE_PANEL: (state, { payload }) => state .update('hiddenPanel', arr => { const index = arr.indexOf(payload); if (index !== -1) { return [ ...arr.slice(0, index), ...arr.slice(index + 1), ]; } return arr.concat(payload); }).set('maximumPanel', ''), MAXIMIZE_PANEL: (state, { payload }) => state
export default Immutable.from({ sites: [ { id: 1, siteName: 'SurferMag', siteUrl: 'www.surfermag.com', description: 'This is the description for SurferMag', categoryIds: [ 2 ] }, { id: 2, siteName: 'Ebay', siteUrl: 'www.ebay.com.au', description: 'This is the description for ebay', categoryIds: [ 1 ] }, { id: 3, siteName: 'Robs UI Tips', siteUrl: 'www.awesomeui.com.au', description: 'This is the description for the best site in the world. It is the best:)', categoryIds: [ 4, 3 ] }, { id: 4, siteName: 'Table Tennis Tips - How to not come runners up', siteUrl: 'www.ttt.com', description: 'This is the description for Table Tennis Tips', categoryIds: [ 1, 2, 3, 4 ] } ], categories: [ { id: 1, description: 'Arts & Entertainment' }, { id: 2, description: 'Automotive' }, { id: 3, description: 'Business' }, { id: 4, description: 'Careers' } ], search: { query: '', canSearch: false, results: [] } });
import Immutable from 'seamless-immutable'; import Topo from '../components/Topology/Topo.js'; const initalState = Immutable.from({ nodes: [], links: [], fixedNode: {}, level: 0, filter: [], selectNodes: {}, tag: '', controllerList: [], }); export default (state = initalState, { type, payload }) => { switch (type) { // case 'ADD_NODE': // Topo.addNode(payload); // return state.update("nodes", d => { // return d.concat(payload); // }); // // case 'DEL_NODE': // return state.update("nodes", d => { // return d.slice(0, d.length - 1); // }); // case 'ADD_LINK': // return state.update("links", d => { // return _.uniqWith(d.concat(payload), _.isEqual); // }); // case 'DEL_LINK':
export const TEST_STATE = Immutable.from({ sites: [ { id: 1, siteName: 'React', siteUrl: 'facebook.github.io/react', description: 'A JavaScript library for building user interfaces', categoryIds: [ 2, 3 ] }, { id: 2, siteName: 'Angular 2', siteUrl: 'angular.io', description: 'One framework. Mobile and desktop.', categoryIds: [ 1, 2, 3 ] }, { id: 3, siteName: 'the_coding_love();', siteUrl: 'thecodinglove.com', description: '/* epic gifs for developers */', categoryIds: [ 3, 4 ] }, { id: 4, siteName: 'Reaction GIFS', siteUrl: 'reactiongifs.com', description: 'Say it with a GIF!', categoryIds: [ 4 ] } ], categories: [ { id: 1, description: 'Model View Controller' }, { id: 2, description: 'JavaScript' }, { id: 3, description: 'Coding' }, { id: 4, description: 'Humour' } ], search: { query: '', canSearch: false, results: [] } });