LearnFrenzy
Sign in Take a free test

Spread and Rest Operators · Spread and Rest Coding Problems · Question 4

Immutable list updates for a to-do app in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Implement addTodo, toggleTodo and removeTodo that return new arrays (never mutating the input) for a list of { id, text, done } objects.

Solution
main.js
const addTodo = (todos, text) => [...todos, { id: todos.length + 1, text, done: false }];
const toggleTodo = (todos, id) => todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t));
const removeTodo = (todos, id) => todos.filter((t) => t.id !== id);

const v0 = [];
const v1 = addTodo(addTodo(v0, "Learn spread"), "Practise rest");
const v2 = toggleTodo(v1, 1);
const v3 = removeTodo(v2, 2);

console.log(v3);
console.log(v0.length, v1[0].done, v2[0].done, v1[1] === v2[1]);

Output Verified by running it on Node.js

[ { id: 1, text: 'Learn spread', done: true } ]
0 false true true

Every version is a new array; only the toggled item is copied ({ ...t, done }) and unchanged items are reused (v1[1] === v2[1]), which is exactly what makes React re-renders cheap.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links