Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion src/transformStateWithClones.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,41 @@
* @return {Object[]}
*/
function transformStateWithClones(state, actions) {
// write code here
const history = [];
let currentState = { ...state };

for (const action of actions) {
switch (action.type) {
case 'clear':
currentState = {};
break;

case 'addProperties':
currentState = {
...currentState,
...action.extraData,
};
break;

case 'removeProperties': {
const nextState = { ...currentState };

for (const key of action.keysToRemove) {
delete nextState[key];
}

currentState = nextState;
break;
}

default:
throw new Error(`Unknown action type: ${action.type}`);
}

history.push(currentState);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation works because each case in your switch statement creates a new object and reassigns it to currentState. However, this is not a very robust approach. The task requires pushing a copy of the state to the history.

If you were to later change one of the cases to mutate currentState directly, all previous states in the history array would also be changed. To prevent such bugs and follow the requirement, you should always push an explicit copy: history.push({ ...currentState });.

}

return history;
}

module.exports = transformStateWithClones;