Skip to content

CodeNot attempted

NotesStore class

Difficulty: easy

Build a NotesStore with addNote(state, name) and getNotes(state).

  • valid states: completed, active, others
  • addNote throws Error('Name cannot be empty') for an empty name
  • both methods throw an Error with message Invalid state <state> (e.g. Invalid state done) for unknown states
  • getNotes returns names in insertion order; stores don't share notes
Show reference solution
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;
}
}
Loading editor…