Simple Text Editor

  • + 0 comments

    My answer with Typescript, i create classes to easy resusable

    class SEditor {
        private _stacks: string[];
        private _stacks_cursor: number;
        private get s() { return this._stacks[this._stacks_cursor] }
        
        /**
         * Simple editor with a [stacks] stored string state after every steps,
         * Can undo & redo with [cursor], [redo] will be overriden by [append]&[delete]
         */
        
        constructor(s: string, private ws: WriteStream) {
            this._stacks = [s]
            this._stacks_cursor = 0
        }
    
        public _append(w: string): void {
            this._stacks.splice(this._stacks_cursor + 1)
            this._stacks.push(this.s + w)
            this._stacks_cursor++
        }
        public _delete(k: number): void {
            this._stacks.splice(this._stacks_cursor + 1)
            this._stacks.push(this.s.substring(0, this.s.length - k))
            this._stacks_cursor++
        }
        public _print(k: number): void { this.ws.write(this.s[k - 1] + '\n'); }
        public _undo(): void { this._move_cursor(-1) }
        public _redo(): void { this._move_cursor(+1) }
    
        private _move_cursor(steps: number): void {
            this._stacks_cursor = Math.max(0, Math.min(this._stacks_cursor + steps, this._stacks.length - 1));
        }
    }
    function main() {
        const ws: WriteStream = createWriteStream(process.env['OUTPUT_PATH']);
        const q: number = parseInt(readLine().trim(), 10);
        const s = new SEditor('', ws)
    
        for (let i = 0; i < q; i++) {
            let [t, w] = readLine().split(' ');
            switch (t) {
                case '1': s._append(w); break;
                case '2': s._delete(parseInt(w, 10)); break;
                case '3': s._print(parseInt(w, 10)); break;
                case '4': s._undo(); break;
            }
        }
    }