示例工程 32-capstone-quality-gates

32-capstone-quality-gates/01-app-skeleton/src/main.ts

typescript · 1.4 KB

运行:32 · app-skeleton

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

export interface Todo {
  id: number;
  title: string;
  done: boolean;
}
 
export type Action =
  | { type: 'add'; title: string }
  | { type: 'toggle'; id: number }
  | { type: 'clear' };
 
export function reduce(state: readonly Todo[], action: Action): Todo[] {
  switch (action.type) {
    case 'add': {
      const nextId = state.reduce((max, todo) => Math.max(max, todo.id), 0) + 1;
      return [...state, { id: nextId, title: action.title, done: false }];
    }
    case 'toggle':
      return state.map((todo) =>
        todo.id === action.id ? { ...todo, done: !todo.done } : todo,
      );
    case 'clear':
      return state.filter((todo) => !todo.done);
    default:
      return assertNever(action);
  }
}
 
function assertNever(value: never): never {
  throw new Error(`unreachable action: ${JSON.stringify(value)}`);
}
 
export function render(state: readonly Todo[]): string {
  return state
    .map((todo) => `${todo.done ? '[x]' : '[ ]'} ${todo.id}.${todo.title}`)
    .join('\n');
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  let state: readonly Todo[] = [];
  state = reduce(state, { type: 'add', title: 'write' });
  state = reduce(state, { type: 'add', title: 'test' });
  state = reduce(state, { type: 'toggle', id: 1 });
  const lines = render(state).split('\n');
  for (const line of lines) {
    log(line);
  }
  return lines;
}