Skip to content

Instantly share code, notes, and snippets.

@BetterProgramming
Created September 9, 2020 15:50
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 BetterProgramming/e99c775e288108d3148d1457f4062582 to your computer and use it in GitHub Desktop.
Save BetterProgramming/e99c775e288108d3148d1457f4062582 to your computer and use it in GitHub Desktop.
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