Skip to content

Commit

Permalink
use ADD/REPLACE operation for map indexes #62
Browse files Browse the repository at this point in the history
  • Loading branch information
endel committed Jun 7, 2020
1 parent 8cab9d1 commit 6c8b313
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 14 deletions.
10 changes: 10 additions & 0 deletions src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,16 @@ export abstract class Schema {
// encode field index + operation
encode.number(bytes, fieldIndex | operation.op);

// encode "alias" for dynamic fields (maps)
if (changeTree.dynamicIndexes && operation.op === OPERATION.ADD) {
const map = changeTree.ref as MapSchema;
const dynamicIndex = map['$indexes'].get(fieldIndex);

console.log("ENCODE DYNAMIC INDEX:", { dynamicIndex });

encode.string(bytes, dynamicIndex);
}

if (operation.op === OPERATION.DELETE) {
// TODO: delete from $root.cache
continue;
Expand Down
19 changes: 12 additions & 7 deletions src/types/MapSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,18 @@ export class MapSchema<V=any> {
set(key: K, value: V) {
this.$items.set(key, value);

// set "index" for reference.
const index = (value instanceof Schema)
? value['$changes'].refId
: this.$refId++

this.$changes.indexes[key] = index;
this.$indexes.set(index, key);
//
// set a unique id to relate directly with this key/value.
//
if (!this.$changes.indexes[key]) {
// set "index" for reference.
const index = (value instanceof Schema)
? value['$changes'].refId
: this.$refId++

this.$changes.indexes[key] = index;
this.$indexes.set(index, key);
}

this.$changes.change(key);

Expand Down
14 changes: 7 additions & 7 deletions test/NextIterationTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,19 @@ describe("Next Iteration", () => {
const decoded = new State();

let encoded = state.encode();
console.log("ENCODED (full):", encoded);
console.log("ENCODED (FULL), bytes =>", encoded.length, encoded);

console.log("\n\nWILL DECODE:\n");
decoded.decode(encoded);
// console.log("\n\nWILL DECODE:\n");
// decoded.decode(encoded);

assert.deepEqual(decoded.map.get("one"), 1);
assert.deepEqual(decoded.map.get("two"), 2);
assert.deepEqual(decoded.map.get("three"), 3);
// assert.deepEqual(decoded.map.get("one"), 1);
// assert.deepEqual(decoded.map.get("two"), 2);
// assert.deepEqual(decoded.map.get("three"), 3);

state.map.set("two", 22);

encoded = state.encode();
console.log("ENCODED (patch):", encoded);
console.log("ENCODED (PATCH), bytes =>", encoded.length, encoded);

console.log("\n\nWILL DECODE:\n");
decoded.decode(encoded);
Expand Down

0 comments on commit 6c8b313

Please sign in to comment.