Created
September 9, 2020 15:50
-
-
Save BetterProgramming/e99c775e288108d3148d1457f4062582 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
const fs = require('fs') | |
const path = require('path') | |
const weightFile = path.join(__dirname, "weightTracker", 'weights.json') | |
class Weight{ | |
constructor(){ | |
this.weights = [] | |
let content = fs.readFileSync(weightFile, {encoding: 'utf-8'}) | |
if (content){ | |
this.weights = JSON.parse(content) | |
} | |
} | |
add(weight){ | |
let date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '') | |
let newWeight = { | |
date: date, | |
weight: weight | |
} | |
this.weights.push(newWeight) | |
this.saveWeight() | |
} | |
show(count){ | |
let len = this.weights.length | |
if (count && len>count){ | |
return this.weights.slice(len - count, len) | |
} | |
return this.weights | |
} | |
saveWeight(){ | |
if (!fs.existsSync(path.dirname(weightFile))){ | |
fs.mkdirSync(path.dirname(weightFile)) | |
} | |
const records = JSON.stringify(this.weights) | |
fs.writeFileSync(weightFile, records, {encoding: 'utf-8'}) | |
} | |
} | |
module.exports = Weight |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment