Saltar al contenido

CódigoSin intentar

Clase NotesStore

Dificultad: fácil

Construye un NotesStore con addNote(state, name) y getNotes(state).

  • estados válidos: completed, active, others
  • addNote lanza Error('Name cannot be empty') si el nombre está vacío
  • ambos métodos lanzan un Error con el mensaje Invalid state <state> (p. ej. Invalid state done) para estados desconocidos
  • getNotes devuelve los nombres en orden de inserción; los stores no comparten notas
Ver solución de referencia
type State = 'completed' | 'active' | 'others';
export class NotesStore {
private notes: { state: State; name: string }[] = [];
private validStates = ['completed', 'active', 'others'];
addNote(state: State, name: string): void {
if (name === '') {
throw new Error('Name cannot be empty');
}
if (!this.validStates.includes(state)) {
throw new Error(`Invalid state ${state}`);
}
this.notes.push({ state, name });
}
getNotes(state: State): string[] {
if (!this.validStates.includes(state)) {
throw new Error(`Invalid state ${state}`);
}
const result: string[] = [];
for (const note of this.notes) {
if (note.state === state) {
result.push(note.name);
}
}
return result;
}
}
Cargando editor…