Skip to content

Instantly share code, notes, and snippets.

@zaydek
Created February 28, 2021 13:16
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/f9c5991c3cb4467737c070d7960670a7 to your computer and use it in GitHub Desktop.
Save zaydek/f9c5991c3cb4467737c070d7960670a7 to your computer and use it in GitHub Desktop.
// prettier-ignore
interface Todo {
id: string
done: boolean
text: string
reset(): void
setDone(done: boolean): void
setText(text: string): void
}
function Todo(this: Todo, { done, text }: { done: boolean; text: string } = { done: false, text: "" }) {
// State
const id = Math.random().toString(36).slice(2, 4)
Object.assign(this, {
id,
done,
text,
})
// Methods
Object.assign(this, {
reset,
setDone,
setText,
})
return this
}
// reset resets the current todo state.
function reset(this: Todo) {
this.done = false
this.text = ""
}
// setDone sets the current todo "done" state.
function setDone(this: Todo, done: boolean) {
this.done = done
}
// setText sets the current todo "text" state.
function setText(this: Todo, text: string) {
this.text = text
}
////////////////////////////////////////////////////////////////////////////////
// prettier-ignore
interface TodoApp {
todo: Todo
todos: Todo[]
add(): void
remove(id: string): void
}
function TodoApp(this: TodoApp) {
// State
Object.assign(this, {
//@ts-ignore
todo: new Todo(),
todos: [],
})
// Methods
Object.assign(this, {
add,
remove,
})
return this
}
// add adds the current todo to the start of the stack.
function add(this: TodoApp) {
if (this.todo.text === "") return
this.todos = [this.todo, ...this.todos]
//@ts-ignore
this.todo = new Todo() // Reset
}
// remove removes an todo.
function remove(this: TodoApp, id: string) {
this.todos = this.todos.filter(each => each.id !== id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment