Skip to content

Commit 2bb9133

Browse files
committed
feat(json-crdt): 🎸 add ArrApi.upd() method
1 parent f38c487 commit 2bb9133

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

src/json-crdt/model/api/__tests__/ArrayApi.spec.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,28 @@ test('can insert a value and delete all previous ones', () => {
1414
expect(arr.view()).toEqual([42, 69]);
1515
});
1616

17-
test('.length()', () => {
18-
const doc = Model.create();
19-
doc.api.set({
20-
arr: [1, 2, 3],
17+
describe('.length()', () => {
18+
test('returns "arr" length', () => {
19+
const doc = Model.create();
20+
doc.api.set({
21+
arr: [1, 2, 3],
22+
});
23+
const arr = doc.api.arr(['arr']);
24+
expect(arr.length()).toBe(3);
25+
});
26+
});
27+
28+
describe('.upd()', () => {
29+
test('can update array element', () => {
30+
const doc = Model.create([1, 2, 3]);
31+
const arr = doc.$.$!;
32+
expect(arr.view()).toEqual([1, 2, 3]);
33+
arr.upd(1, 42);
34+
expect(arr.view()).toEqual([1, 42, 3]);
35+
arr.upd(2, 69);
36+
arr.upd(1, 24);
37+
expect(arr.view()).toEqual([1, 24, 69]);
2138
});
22-
const arr = doc.api.arr(['arr']);
23-
expect(arr.length()).toBe(3);
2439
});
2540

2641
describe('events', () => {

src/json-crdt/model/api/nodes.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -752,6 +752,17 @@ export class ArrApi<N extends ArrNode<any> = ArrNode<any>> extends NodeApi<N> {
752752
api.apply();
753753
}
754754

755+
// TODO: Implement `.push()` method.
756+
757+
public upd(index: number, value: JsonNodeView<N>[number]): void {
758+
const {api, node} = this;
759+
const ref = node.getId(index);
760+
if (!ref) throw new Error('OUT_OF_BOUNDS');
761+
const {builder} = api;
762+
builder.updArr(node.id, ref, builder.constOrJson(value));
763+
api.apply();
764+
}
765+
755766
/**
756767
* Deletes a range of elements at a given position.
757768
*

0 commit comments

Comments
 (0)