Skip to content
Source
Sign inSign up
TanStack/showcase
A read-only demo of every feature
Every page of this repository is open, and nothing can change. Take a guided tour of what TanStack Source does.
Open History to see the last commit

tasks.ts

39 lines1.4 KB

1/** One task of a list. */
2export type Task = {
3 id: number
4 title: string
5 done: boolean
6 /** Lower numbers come first. */
7 priority: number
8}
9​
10/** A list of tasks. Every function returns a new list and never changes the one it gets. */
11export type TaskList = ReadonlyArray<Task>
12​
13/**
14 * Adds a task at the end of `list`, with the next free id.
15 *
16 * @example addTask([], 'Write the docs') // [{ id: 1, title: 'Write the docs', done: false, priority: 3 }]
17 */
18export function addTask(list: TaskList, title: string, priority = 3): TaskList {
19 const name = title.trim()
20 if (name === '') throw new Error('A task needs a title.')
21 if (priority < 0) throw new Error('A priority is 0 or more.')
22 const id = list.reduce((max, task) => Math.max(max, task.id), 0) + 1
23 return [...list, { id, title: name, done: false, priority }]
25​
26/** Marks the task `id` as done. A list without that id comes back unchanged. */
27export function completeTask(list: TaskList, id: number): TaskList {
28 return list.map((task) => (task.id === id ? { ...task, done: true } : task))
30​
31/** Removes the task `id`. */
32export function removeTask(list: TaskList, id: number): TaskList {
33 return list.filter((task) => task.id !== id)
35​
36/** The open tasks, the most important first. Tasks with the same priority keep their order. */
37export function openTasks(list: TaskList): TaskList {
38 return list.filter((task) => !task.done).toSorted((a, b) => a.priority - b.priority)