Last active
April 3, 2019 23:50
-
-
Save wooosh/a4f2757b59e883516ee1b60e723b33f4 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') | |
// Define class for quick object store | |
class QuickStore { | |
constructor(loc="quickstore.json") { | |
this.loc = loc; | |
this.memObj = {}; | |
this.queue = []; | |
try { | |
this.memObj = JSON.parse(fs.readFileSync(this.loc)); | |
} | |
catch (e) { | |
if (e.code = 'ENOENT') { | |
this.memObj = {}; | |
} | |
} | |
} | |
update() { | |
fs.writeFile(this.loc, JSON.stringify(this.memObj, null, 2), (err) => { | |
if (err) throw err; | |
}); | |
} | |
setVal(key, data, array=false) { | |
const keys = key.split("."); | |
let pointer = this.memObj; | |
keys.forEach(k => { | |
if (keys.indexOf(k) == keys.length - 1) { | |
if (array) pointer[k] = (pointer[k] && pointer[k].concat(data)) || [data]; | |
else pointer[k] = data; | |
} | |
else if (!pointer.hasOwnProperty(k)) { | |
pointer[k] = {}; | |
} | |
pointer = pointer[k] | |
}); | |
this.update() | |
} | |
set(key, data) { | |
this.setVal(key, data); | |
} | |
push(key, data) { | |
this.setVal(key, data, true) | |
} | |
add(key, data) { | |
if (this.get(key) == undefined) { | |
this.set(key, data) | |
} | |
else this.set(key, this.get(key) + data) | |
} | |
get(key) { | |
const keys = key.split(".") | |
let pointer = this.memObj; | |
keys.forEach(k => pointer = pointer[k]) | |
return pointer; | |
} | |
} | |
let db = new QuickStore('test.json') | |
// Setting an object in the database: | |
db.set('userInfo', { difficulty: 'Easy' }) | |
// -> { difficulty: 'Easy' } | |
// | |
// Pushing an element to an array (that doesn't exist yet) in an object: | |
db.push('userInfo.items', 'Sword') | |
// -> { difficulty: 'Easy', items: ['Sword'] } | |
// | |
// Adding to a number (that doesn't exist yet) in an object: | |
db.add('userInfo.balance', 500) | |
// -> { difficulty: 'Easy', items: ['Sword'], balance: 500 } | |
// | |
// Repeating previous examples: | |
db.push('userInfo.items', 'Watch') | |
// -> { difficulty: 'Easy', items: ['Sword', 'Watch'], balance: 500 } | |
db.add('userInfo.balance', 500) | |
// -> { difficulty: 'Easy', items: ['Sword', 'Watch'], balance: 1000 } | |
// | |
// Fetching individual properties | |
console.log(db.get('userInfo.balance')) // -> 1000 | |
console.log(db.get('userInfo.items')) // ['Sword', 'Watch'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment