Design a Text Editor LeetCode solution in JavaScript

1
var TextEditor = function () {
2
this.forward = [];
3
this.backward = [];
4
};
5

6
/**
7
* @param {string} text
8
* @return {void}
9
*/
10
TextEditor.prototype.addText = function (text) {
11
for (let letter of text) {
12
this.forward.push(letter);
13
}
14
};
15

16
/**
17
* @param {number} k
18
* @return {number}
19
*/
20
TextEditor.prototype.deleteText = function (k) {
21
let deleted = 0;
22
while (this.forward.length && deleted < k) {
23
this.forward.pop();
24
deleted++;
25
}
26
return deleted;
27
};
28

29
/**
30
* @param {number} k
31
* @return {string}
32
*/
33
TextEditor.prototype.cursorLeft = function (k) {
34
let moved = 0;
35
while (this.forward.length && moved < k) {
36
this.backward.push(this.forward.pop());
37
moved++;
38
}
39
return toTheLeft(this.forward);
40
};
41

42
/**
43
* @param {number} k
44
* @return {string}
45
*/
46
TextEditor.prototype.cursorRight = function (k) {
47
let moved = 0;
48
while (moved < k && this.backward.length) {
49
this.forward.push(this.backward.pop());
50
moved++;
51
}
52
return toTheLeft(this.forward);
53
};
54

55
function toTheLeft(arr) {
56
let letters = [];
57
for (let i = Math.max(0, arr.length - 10); i < arr.length; i++) {
58
letters.push(arr[i]);
59
}
60
let res = letters.join("");
61
return res;
62
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0