Skip to content

Commit e9f7a79

Browse files
committed
feat(json-crdt): 🎸 implement ArrApi.push() method
1 parent 2bb9133 commit e9f7a79

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {s} from '../../../../json-crdt-patch';
1+
import {nodes, s} from '../../../../json-crdt-patch';
22
import {Model} from '../../Model';
33

44
test('can insert a value and delete all previous ones', () => {
@@ -25,6 +25,22 @@ describe('.length()', () => {
2525
});
2626
});
2727

28+
describe('.push()', () => {
29+
test('can append elements to the end of array', () => {
30+
const doc = Model.create(s.arr<nodes.con<number>>([]));
31+
const arr = doc.$.$!;
32+
expect(arr.view()).toEqual([]);
33+
arr.push(1);
34+
expect(arr.view()).toEqual([1]);
35+
arr.push(2, 3);
36+
expect(arr.view()).toEqual([1, 2, 3]);
37+
arr.push(4);
38+
expect(arr.view()).toEqual([1, 2, 3, 4]);
39+
arr.push(5, 6, 7);
40+
expect(arr.view()).toEqual([1, 2, 3, 4, 5, 6, 7]);
41+
});
42+
});
43+
2844
describe('.upd()', () => {
2945
test('can update array element', () => {
3046
const doc = Model.create([1, 2, 3]);

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

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -738,8 +738,7 @@ export class ArrApi<N extends ArrNode<any> = ArrNode<any>> extends NodeApi<N> {
738738
* Inserts elements at a given position.
739739
*
740740
* @param index Position at which to insert elements.
741-
* @param values JSON/CBOR values or IDs of the values to insert.
742-
* @returns Reference to itself.
741+
* @param values Values or schema of the elements to insert.
743742
*/
744743
public ins(index: number, values: Array<JsonNodeView<N>[number]>): void {
745744
const {api, node} = this;
@@ -752,8 +751,22 @@ export class ArrApi<N extends ArrNode<any> = ArrNode<any>> extends NodeApi<N> {
752751
api.apply();
753752
}
754753

755-
// TODO: Implement `.push()` method.
754+
/**
755+
* Inserts elements at the end of the array.
756+
*
757+
* @param values Values or schema of the elements to insert at the end of the array.
758+
*/
759+
public push(...values: JsonNodeView<N>[number][]): void {
760+
const length = this.length();
761+
this.ins(length, values);
762+
}
756763

764+
/**
765+
* Updates (overwrites) an element at a given position.
766+
*
767+
* @param index Position at which to update the element.
768+
* @param value Value or schema of the element to replace with.
769+
*/
757770
public upd(index: number, value: JsonNodeView<N>[number]): void {
758771
const {api, node} = this;
759772
const ref = node.getId(index);

0 commit comments

Comments
 (0)