Last active
July 31, 2021 10:08
-
-
Save ZeroX-DG/7527cd6ea977f327b33c43f96b439c06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For beginners like me:
const api = new TodoAPI
is valid syntax. Thenew
operator allows parenthesis to be omitted if there are no arguments.Both
const api = new TodoAPI
andconst api = new TodoAPI()
are the same.Reference: StackOverflow