UNPKG

zetabasejs

Version:

A NoSQL database for quick deployment.

96 lines (81 loc) 2.55 kB
const crypto = require("crypto"); const NodePtr = require("./NodePtr"); const Stack = require("./Stack"); const Deprecator = require("../Deprecator"); class DataNode { constructor(id, data) { this.id = id; this.data = data ? data : null; this.childNodes = new Object(); } add(id, data) { this.childNodes[id] = new DataNode(id, data); return this; } push(data) { let id = DataNode.key(); this.childNodes[id] = new DataNode(id, data); return id; } get(id) { return this.childNodes[id]; } remove(id) { this.childNodes[id] = null; delete this.childNodes[id]; } has(id) { return this.childNodes.hasOwnProperty(id); } static keyPrefix(prefix="ZETABASE_KEY") { return crypto.createHash("md5").update(prefix).digest('base64').substr(0, 5).toString('hex') } static key() { return crypto.createHash("md5").update(new Date().getTime() + Math.random().toString()).digest("hex") + DataNode.keyPrefix(); } list(callback) { Object.keys(this.childNodes).map(childNodeKey => callback( this.childNodes[childNodeKey].data, //data childNodeKey, //key this.childNodes[childNodeKey] //dataNode ) ) } childKeys() { return Object.keys(this.childNodes); } traverse(id) { let cur = this; let next = this.childNodes[id]; return new NodePtr(cur, next); } size() { return Object.keys(this.childNodes).length; } isEmpty() { return this.data === null && this.size() === 0; } static fromObject(obj) { let dataNode = new DataNode("/", null); if (obj.hasOwnProperty("data")) dataNode.data = obj.data; if (obj.childNodes) Object.keys(obj.childNodes).map((childNodeKey) => { dataNode.childNodes[childNodeKey] = DataNode.fromObject(obj.childNodes[childNodeKey]); }) return dataNode; } /* The below functions are deprecated. */ iterate(callback) { Object.keys(this.childNodes).map(childNodeKey => callback( childNodeKey, //key this.childNodes[childNodeKey].data, //data this.childNodes[childNodeKey] //dataNode ) ) } } module.exports = DataNode;