-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
OpFlip.ts
49 lines (42 loc) · 1.29 KB
/
OpFlip.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import type {CompactFlipOp, OPCODE_FLIP} from '../codec/compact/types';
import {AbstractOp} from './AbstractOp';
import {OperationFlip} from '../types';
import {find, Path, formatJsonPointer} from '../../json-pointer';
import {OPCODE} from '../constants';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
/**
* @category JSON Patch Extended
*/
export class OpFlip extends AbstractOp<'flip'> {
constructor(path: Path) {
super(path);
}
public op() {
return 'flip' as 'flip';
}
public code() {
return OPCODE.flip;
}
public apply(doc: unknown) {
const ref = find(doc, this.path);
if (ref.obj) (ref as any).obj[(ref as any).key] = !ref.val;
else doc = !ref.val;
return {doc, old: ref.val};
}
public toJson(parent?: AbstractOp): OperationFlip {
const op: OperationFlip = {
op: 'flip',
path: formatJsonPointer(this.path),
};
return op;
}
public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactFlipOp {
const opcode: OPCODE_FLIP = verbose ? 'flip' : OPCODE.flip;
return [opcode, this.path];
}
public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
encoder.encodeArrayHeader(2);
encoder.writer.u8(OPCODE.flip);
encoder.encodeArray(this.path as unknown[]);
}
}