Skip to content

Study Planner Core

The Course
•
17 min study

Two small tools for updating one item

The planner needs to mark one session done without changing the others. Two pieces of syntax make that short.

The callback's second parameter. map and filter call your callback with the item and its index. You can ignore the index (as on Day 4) or name it:

JavaScript
const topics = ["Loops", "Arrays", "Objects"];
const labelled = topics.map((topic, position) => position + ": " + topic);
console.log(labelled.join(", "));  // 0: Loops, 1: Arrays, 2: Objects

The conditional operator ? :. condition ? a : b is an expression that gives a when the condition is true and b when it is false. It is a compact if/else that produces a value, so it fits inside a callback:

JavaScript
const minutes = 50;

// with if/else
let label;
if (minutes >= 45) {
  label = "long";
} else {
  label = "short";
}

// the same choice as one expression
const sameLabel = minutes >= 45 ? "long" : "short";
console.log(label, sameLabel);  // long long

Use ? : for choosing between two values; keep if/else when each branch does several things. Together, sessions.map((session, position) => position === index ? changed : session) means: "for the item at index, use a changed copy; keep every other item as it is."

Predict before running

Does completing the copied plan change the original record? After running, add a second session and complete index 1.

Predict, then run JavaScript
function addSession(sessions, topic, minutes) {
  return [...sessions, { topic, minutes, done: false }];
}

function completeAt(sessions, index) {
  if (!Number.isInteger(index) || index < 0 || index >= sessions.length) {
    throw new Error("Unknown session");
  }

  return sessions.map((session, position) =>
    position === index ? { ...session, done: true } : session
  );
}

const plan = addSession([], "Loops", 25);
const finished = completeAt(plan, 0);

console.log(plan[0].done);
console.log(finished[0].done);
Check your prediction
Text
false
true

Trace each statement in order. If your prediction differed, describe the first place your mental model and the result diverged before trying again.

Compare an index with a stable identity

The core example above identifies a record by its current array position. The example below compares a different design: giving each record a permanent numeric id. These are two alternatives, not code you must mix together. The integration lesson will practice updating by id; the final browser app keeps the simpler fixed-order index design.

An array position changes when records are removed or sorted. A record ID should keep referring to the same item. Use an increasing counter for this small in-memory program; a real shared service would need a stronger strategy. Keep the counter outside the creation function so it survives between calls.

shift() removes the first item from an array (whereas pop removes the last). In id: nextId++, the current counter becomes the id and the counter increases afterward. For clarity, you could instead save const id = nextId;, then write nextId = nextId + 1;, and return a record using id.

Choose a stable identity JavaScript
let nextId = 1;

function createSession(topic) {
  return { id: nextId++, topic, done: false };
}

const sessions = [createSession("Loops"), createSession("Arrays")];

sessions.shift();
sessions.push(createSession("Functions"));
console.log(sessions.map(item => item.id).join(", "));
Check your prediction
Text
2, 3

Postfix ++ uses the current value and then increments it. Removing the first item does not cause its ID to be reused.

Before you move on

Keep one list of sessions and calculate totals from it when asked, instead of updating a separate total on every change. Test one valid add, one rejected add, and two sessions where only one is done.

Your turn

Exercise

Study Planner Core: practice

Write removeAt(sessions, index) using filter. Reject a noninteger, negative, or out-of-range index using throw new Error("Unknown session"). An omitted index is invalid too. Removing index 0 from two records should leave Arrays without changing the original length of 2.

Your working space JavaScript
// Write removeAt, then try two records and index 0.
Hint 1: the idea

Filter keeps the positions other than the one being removed.

Hint 2: a first step

Copy the index guard from completeAt into removeAt first, and check that removeAt([], 0) throws. Then think about which positions filter should keep.

Show one solution
JavaScript
function removeAt(sessions, index) {
  if (!Number.isInteger(index) || index < 0 || index >= sessions.length) {
    throw new Error("Unknown session");
  }

  return sessions.filter((session, position) => position !== index);
}

const plan = [{ topic: "Loops" }, { topic: "Arrays" }];
const remaining = removeAt(plan, 0);

console.log(remaining[0].topic);
console.log(plan.length);
Text
Arrays
2

This function changes list membership without changing the input array. Try an invalid index and confirm it is rejected; restore valid input when you finish.

What you should be able to explain

  • Why is an index a fragile identity?
  • Which function owns creating a record?
  • What should happen when a requested ID does not exist?

Was this article helpful?

Your response is saved on this device.