1/* 2 * Copyright (c) 2022-2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16export class EditStack<T> { 17 private stack: T[] = []; 18 private currentPosition: number = -1; 19 20 isRedoValid(): boolean { 21 return (this.currentPosition < this.stack.length - 1); 22 } 23 24 isUndoValid(): boolean { 25 return (this.currentPosition >= 0); 26 } 27 28 redo(): number { 29 if (this.isRedoValid()) { 30 this.currentPosition++; 31 } 32 return this.currentPosition; 33 } 34 35 undo(): number { 36 if (this.isUndoValid()) { 37 this.currentPosition--; 38 } 39 return this.currentPosition; 40 } 41 42 reset(): void { 43 this.stack.length = 0; 44 this.currentPosition = -1; 45 } 46 47 getLength(): number { 48 return this.stack.length; 49 } 50 51 getPosition(): number { 52 return this.currentPosition; 53 } 54 55 at(index: number): T { 56 return this.stack[index]; 57 } 58 59 push(obj: T): void { 60 let reserveLength = this.currentPosition + 1; 61 if (reserveLength < this.stack.length) { 62 this.stack.length = reserveLength; 63 } 64 this.currentPosition = this.stack.push(obj) - 1; 65 } 66 67 forEach(action: Function, count: number = this.currentPosition): void { 68 for (let i = 0; i <= count; ++i) { 69 action(this.stack[i]); 70 } 71 } 72}