Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Ionic Practice Exercises

Practice native-app logic with eight exercises on permissions, storage, sync, lists, versions and testing; each has runnable starter code, checks and a worked solution.

Reading about mobile development helps, and writing code makes it stick. These exercises practice the logic behind the Capacitor, storage, sync, testing and release lessons. Each one has starter code that runs and a few checks. Edit the code until the checks print PASS. The solutions come after the exercises; try each one for at least ten minutes before looking.

The UI parts of Ionic need a real project, so the exercises focus on the code that decides how your app behaves. That logic is what you will unit test in a real app.

Exercise 1: permission state

Write canUseCamera(status). It receives 'granted', 'prompt', 'prompt-with-rationale' or 'denied' and returns an object { action, message }: for granted the action is use; for prompt and prompt-with-rationale it is ask; for denied it is settings. Anything else must throw.

JS Exercise 1: permission decisions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 2: safe JSON storage

Complete makeStore(backing), which wraps an async key-value backing store (strings only). set(key, obj) stores JSON; get(key, fallback) returns the parsed value, or fallback when the key is missing or the stored text is invalid JSON.

JS Exercise 2: a JSON wrapper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 3: the outbox order

Write nextOperation(outbox, now). The outbox is an array of { id, tries, retryAt }. Return the first operation whose retryAt <= now, but never skip an earlier operation that is waiting for the same noteId (keep per-note order). Return null if nothing is ready.

JS Exercise 3: pick the next operation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 4: windowed list

Write window(total, rowHeight, viewportHeight, scrollTop) returning { start, end } (end exclusive) with a buffer of 2 rows on each side, clamped to 0..total.

JS Exercise 4: virtual list window

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 5: should the app update?

Write updateKind(installed, latest, minSupported) returning 'force' if installed is below minSupported, 'optional' if below latest, otherwise 'none'. Versions are major.minor.patch; compare numerically, not as strings.

JS Exercise 5: force or optional update

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 6: permission texts

Write lintUsageText(text) returning an array of problems: 'too short' (fewer than 6 words), 'no app name' (does not contain "Trail Notes"), 'generic' (text equals "needs access" ignoring case). An empty array means the text is fine.

JS Exercise 6: lint a usage description

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 7: debounced search state

Write createSearch(clock, wait, onSearch) which returns a function type(text). After wait ms of silence, onSearch is called once with the latest text. Use clock.setTimeout and clock.clearTimeout (provided, with an advance(ms) helper).

JS Exercise 7: debounce with a fake clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 8: a test for your own code

Write two tests, using the mini test and expect helpers, for the function slugify(text) provided: it must lowercase, trim and replace runs of non-alphanumerics with a single dash. Add at least one edge case test of your own, then find the bug in slugify (hint: leading and trailing dashes).

JS Exercise 8: find the bug with a test

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions

Open each only after trying. They are plain JavaScript.

JavaScript
// 1
function canUseCamera(status) {
  switch (status) {
    case 'granted': return { action: 'use', message: 'Camera ready' };
    case 'prompt':
    case 'prompt-with-rationale': return { action: 'ask', message: 'Explain, then ask' };
    case 'denied': return { action: 'settings', message: 'Open Settings to enable the camera' };
    default: throw new Error('Unknown status: ' + status);
  }
}

// 2
async set(key, value) { await backing.setItem(key, JSON.stringify(value)); },
async get(key, fallback) {
  const text = await backing.getItem(key);
  if (text === null) return fallback;
  try { return JSON.parse(text); } catch { return fallback; }
},

// 3
function nextOperation(outbox, now) {
  const blocked = new Set();
  for (const op of outbox) {
    if (!blocked.has(op.noteId) && op.retryAt <= now) return op;
    blocked.add(op.noteId);          // a waiting op blocks later ops of the same note
  }
  return null;
}

// 4
function window_(total, rowHeight, viewportHeight, scrollTop) {
  const first = Math.floor(scrollTop / rowHeight);
  const count = Math.ceil(viewportHeight / rowHeight);
  return { start: Math.max(0, first - 2), end: Math.min(total, first + count + 2) };
}

// 5
function updateKind(installed, latest, minSupported) {
  const cmp = (a, b) => {
    const x = a.split('.').map(Number), y = b.split('.').map(Number);
    for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
    return 0;
  };
  if (cmp(installed, minSupported) < 0) return 'force';
  if (cmp(installed, latest) < 0) return 'optional';
  return 'none';
}

// 6
function lintUsageText(text) {
  const problems = [];
  if (text.trim().split(/\s+/).length < 6) problems.push('too short');
  if (!text.includes('Trail Notes')) problems.push('no app name');
  if (text.trim().toLowerCase() === 'needs access') problems.push('generic');
  return problems;
}

// 7
return function type(text) {
  clock.clearTimeout(timer);
  timer = clock.setTimeout(() => onSearch(text), wait);
};
// (declare `let timer;` above the returned function)

// 8: slugify('  Hello!  ') returns 'hello-'. Fix:
//    .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')

After the solutions, change the requirements and adapt them: make Exercise 3 retry with exponential backoff, or make Exercise 4 support rows of two heights. Changing a solution proves you understand it.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why does Exercise 3 block later operations of the same note?

    Order per record matters, while unrelated records can proceed independently.
  2. 2. Why compare version numbers numerically?

    As text, '1.10.0' is smaller than '1.9.0', which gives wrong update decisions.
  3. 3. What should a failing test teach you in Exercise 8?

    A failing test is information. Here the code has a real edge case bug.

Summary

  • Small pure functions carry most app decisions: permissions, versions, ordering and windows.
  • Make them testable by passing in time, storage and plugins.
  • Write the edge cases that hurt: empty input, invalid JSON, string versus number comparison.

Next: Ionic Interview Questions