Skip to content

Instantly share code, notes, and snippets.

@ZeroX-DG
Last active July 31, 2021 10:08
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 ZeroX-DG/7527cd6ea977f327b33c43f96b439c06 to your computer and use it in GitHub Desktop.
Save ZeroX-DG/7527cd6ea977f327b33c43f96b439c06 to your computer and use it in GitHub Desktop.
import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
const todoFile = path.join(os.homedir(), 'checkme', 'todos.json')
interface Todo {
done: boolean;
todo: string;
}
class TodoAPI {
private todos : Todo[] = []
constructor () {
this.todos = JSON.parse(fs.readFileSync(todoFile, { encoding: 'utf-8' }))
}
private saveTodos () {
// make folder for the first run
if (!fs.existsSync(path.dirname(todoFile))) {
fs.mkdirSync(path.dirname(todoFile))
}
const data = JSON.stringify(this.todos)
fs.writeFileSync(todoFile, data, { encoding: 'utf-8' })
}
add (todo : string) {
const newTodo : Todo = { done: false, todo }
this.todos.push(newTodo)
this.saveTodos()
}
remove (index : number) {
this.todos.splice(index, 1)
this.saveTodos()
}
list () {
return this.todos
}
get (index : number) : Todo {
return this.todos[index]
}
done (index : number) {
this.todos[index].done = true
this.saveTodos()
}
undone (index : number) {
this.todos[index].done = false
this.saveTodos()
}
}
const api = new TodoAPI
export default api
@bug-author
Copy link

For beginners like me:
const api = new TodoAPI is valid syntax. The new operator allows parenthesis to be omitted if there are no arguments.

Both const api = new TodoAPI and const api = new TodoAPI() are the same.

Reference: StackOverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment