comparison src/app/Session.ts @ 465:caef9a302bec

Add methods for mutating the current state without updating the history (naming might not be that declarative).
author Lucas Thompson <dev@lucas.im>
date Fri, 30 Jun 2017 14:49:40 +0100
parents 2624bb55dbf6
children b963af7e6eaf
comparison
equal deleted inserted replaced
464:50f61d1945db 465:caef9a302bec
70 this.stack = []; 70 this.stack = [];
71 this.history = [[]]; 71 this.history = [[]];
72 this.historyOffset = 0; 72 this.historyOffset = 0;
73 } 73 }
74 74
75 shift(): T { 75 shiftMutating(): T {
76 const item = this.stack[0]; 76 const item = this.stack[0];
77 this.stack = this.stack.slice(1); 77 this.stack = this.stack.slice(1);
78 return item;
79 }
80
81 shift(): T {
82 const item = this.shiftMutating();
78 this.history.push([...this.stack]); 83 this.history.push([...this.stack]);
79 return item; 84 return item;
80 } 85 }
81 86
87 unshiftMutating(item: T): number {
88 this.stack = [item, ...this.stack];
89 return this.stack.length;
90 }
91
82 unshift(item: T): number { 92 unshift(item: T): number {
83 this.stack = [item, ...this.stack]; 93 const newLength = this.unshift(item);
84 this.history.push([...this.stack]); 94 this.history.push([...this.stack]);
85 return this.stack.length; 95 return newLength;
86 } 96 }
87 97
88 findIndex(predicate: (value: T, 98 findIndex(predicate: (value: T,
89 index: number, 99 index: number,
90 array: T[]) => boolean): number { 100 array: T[]) => boolean): number {
98 get(index: number): T { 108 get(index: number): T {
99 return this.stack[index]; 109 return this.stack[index];
100 } 110 }
101 111
102 set(index: number, value: T) { 112 set(index: number, value: T) {
113 this.setMutating(index, value);
114 this.history.push([...this.stack]);
115 }
116
117 setMutating(index: number, value: T) {
103 this.stack = [ 118 this.stack = [
104 ...this.stack.slice(0, index), 119 ...this.stack.slice(0, index),
105 value, 120 value,
106 ...this.stack.slice(index + 1) 121 ...this.stack.slice(index + 1)
107 ]; 122 ];
108 this.history.push([...this.stack]);
109 } 123 }
110 124
111 map<U>(transform: (value: T, index: number, array: T[]) => U): U[] { 125 map<U>(transform: (value: T, index: number, array: T[]) => U): U[] {
112 return this.stack.map(transform); 126 return this.stack.map(transform);
113 } 127 }