Skip to content

Instantly share code, notes, and snippets.

@zaydek
Created March 9, 2021 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaydek/5fd8ca2b227922aea4acabb5d9ba0098 to your computer and use it in GitHub Desktop.
Save zaydek/5fd8ca2b227922aea4acabb5d9ba0098 to your computer and use it in GitHub Desktop.
////////////////////////////////////////////////////////////////////////////////
// Todo
interface Todo {
id: string
done: boolean
text: string
setDone(value?: boolean): void
setText(value: string): void
}
function setDone(this: Todo, value: boolean): void {
this.done = value
}
function setText(this: Todo, value: string): void {
this.text = value
}
function newTodo({ done, text } = { done: false, text: "" }): Todo {
const todo: Todo = {
id: Math.random().toString(36).slice(2, 6),
done,
text,
setDone(value) {
setDone.apply(this, [value ?? true])
},
setText(value) {
setText.apply(this, [value])
},
}
return todo
}
////////////////////////////////////////////////////////////////////////////////
// TodosApp
interface TodosApp {
todo: Todo
todos: Todo[]
addTodo(): void
removeTodoByID(id: string): void
}
function addTodo(this: TodosApp): void {
if (this.todo.text === "") return
this.todos.push(this.todo)
this.todo = newTodo()
}
function removeTodoByID(this: TodosApp, id: string): void {
this.todos = this.todos.filter(todo => todo.id !== id)
}
function newTodosApp(): TodosApp {
const app: TodosApp = {
todo: newTodo(),
todos: [],
addTodo() {
addTodo.apply(this)
},
removeTodoByID(id) {
removeTodoByID.apply(this, [id])
},
}
return app
}
////////////////////////////////////////////////////////////////////////////////
const todosApp = newTodosApp()
console.log(todosApp)
todosApp.todo.setDone()
console.log(todosApp)
todosApp.todo.setText("Hello, world!")
console.log(todosApp)
todosApp.addTodo()
console.log(todosApp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment