Fix keyvalue example

Refactor List
This commit is contained in:
haad 2016-03-04 22:26:20 +01:00
parent 1a0b93d133
commit f9413aa89e
3 changed files with 26 additions and 15 deletions

View File

@ -40,7 +40,6 @@ let run = (async(() => {
} }
} catch(e) { } catch(e) {
console.error("error:", e);
console.error(e.stack); console.error(e.stack);
process.exit(1); process.exit(1);
} }

View File

@ -12,8 +12,9 @@ class List {
this._currentBatch = []; this._currentBatch = [];
} }
/* Methods */
add(data) { add(data) {
const heads = this._findHeads(this.items); const heads = List.findHeads(this.items);
const node = new Node(this.id, this.seq, this.ver, data, heads); const node = new Node(this.id, this.seq, this.ver, data, heads);
this._currentBatch.push(node); this._currentBatch.push(node);
this.ver ++; this.ver ++;
@ -36,20 +37,16 @@ class List {
this.ver = 0; this.ver = 0;
} }
_findHeads(list) { /* Private methods */
return Lazy(list) _commit() {
.reverse() const current = Lazy(this._currentBatch).difference(this._items).toArray();
.indexBy((f) => f.id) this._items = this._items.concat(current);
.pairs() this._currentBatch = [];
.map((f) => f[1]) this.ver = 0;
.filter((f) => !this._isReferencedInChain(list, f)) this.seq ++;
.toArray();
}
_isReferencedInChain(all, item) {
return Lazy(all).find((e) => e.hasChild(item)) !== undefined;
} }
/* Properties */
get items() { get items() {
return this._items.concat(this._currentBatch); return this._items.concat(this._currentBatch);
} }
@ -67,6 +64,7 @@ class List {
} }
} }
/* Static methods */
static fromJson(json) { static fromJson(json) {
let list = new List(json.id); let list = new List(json.id);
list.seq = json.seq; list.seq = json.seq;
@ -77,6 +75,20 @@ class List {
.toArray(); .toArray();
return list; return list;
} }
static findHeads(list) {
return Lazy(list)
.reverse()
.indexBy((f) => f.id)
.pairs()
.map((f) => f[1])
.filter((f) => !List.isReferencedInChain(list, f))
.toArray();
}
static isReferencedInChain(all, item) {
return Lazy(all).find((e) => e.hasChild(item)) !== undefined;
}
} }
module.exports = List; module.exports = List;

View File

@ -23,7 +23,7 @@ class OrbitList extends List {
if(this.ver >= MaxBatchSize) if(this.ver >= MaxBatchSize)
this._commit(); this._commit();
const heads = super._findHeads(this.items); const heads = List.findHeads(this.items);
const node = new Node(this._ipfs, this.id, this.seq, this.ver, data, heads); const node = new Node(this._ipfs, this.id, this.seq, this.ver, data, heads);
node._commit(); // TODO: obsolete? node._commit(); // TODO: obsolete?
this._currentBatch.push(node); this._currentBatch.push(node);