Bitpath

Boss lesson · Unit 08

A task manager

One whole program, from an empty file to tested code

13 exercisesabout 3 min

What you practise

  • One program from an empty file: a data model, commands, asynchronous saving and loading, tests, and a refactor at the end. What to learn next

Try a question from this lesson

Pick one

You are starting a task manager from an empty file. It must add tasks, mark them done and list them. Which shape for one task makes that easiest?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The model

Start with the data, not the screen. The whole state of the program is one array of task objects.

Every change is a small function that takes the list and returns a new list. Functions like that are easy to read, easy to test and safe to combine.

JavaScript
function addTask(tasks, title) {
  const task = {
    id: tasks.length + 1,
    title: title,
    done: false,
  };
  return [...tasks, task];
}
let tasks = [];
tasks = addTask(tasks, "Buy milk");
tasks = addTask(tasks, "Call Bo");
console.log(tasks.length, tasks[1].id);
// 2 2

Concept

Saving takes time

Real storage is slow, so real save and load functions return promises. This pretend disk behaves the same way.

save(tasks) writes the list as JSON text after 10 ms. In the next exercises, load() is its partner: after 5 ms it gives back the parsed list, or an empty array when nothing was saved.

JavaScript
const disk = { text: null };

function save(tasks) {
  return new Promise((resolve) => {
    setTimeout(() => {
      disk.text = JSON.stringify(tasks);
      resolve();
    }, 10);
  });
}

Concept

Tests

A test is code that runs your code and compares the result with the answer you expect.

Write one for the normal case and one for each edge. Run them all after every change: when one says FAIL, you know what you just broke.

Real projects use a test runner. The idea is exactly this.

JavaScript
function test(name, got, want) {
  const ok = got === want;
  console.log(ok ? "ok" : "FAIL", name);
}

function isAdult(age) {
  return age > 18;
}
test("19 is adult", isAdult(19), true);
test("18 is adult", isAdult(18), true);
// ok 19 is adult
// FAIL 18 is adult

9 more exercises in the app

  • 3× type the answer
  • 1× order the lines
  • 3× multiple choice
  • 1× fill the blanks
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy