forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesign a Text Editor.js
66 lines (57 loc) · 1.23 KB
/
Design a Text Editor.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var TextEditor = function() {
this.forward = [];
this.backward = [];
};
/**
* @param {string} text
* @return {void}
*/
TextEditor.prototype.addText = function(text) {
for (let letter of text) {
this.forward.push(letter);
}
};
/**
* @param {number} k
* @return {number}
*/
TextEditor.prototype.deleteText = function(k) {
let deleted = 0;
while (this.forward.length && deleted < k) {
this.forward.pop();
deleted++;
}
return deleted;
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorLeft = function(k) {
let moved = 0;
while (this.forward.length && moved < k) {
this.backward.push(this.forward.pop());
moved++;
}
return toTheLeft(this.forward);
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorRight = function(k) {
let moved = 0;
while (moved < k && this.backward.length) {
this.forward.push(this.backward.pop());
moved++;
}
return toTheLeft(this.forward);
};
function toTheLeft (arr) {
let letters = [];
for (let i = Math.max(0, arr.length - 10); i < arr.length; i++) {
letters.push(arr[i]);
}
let res = letters.join("");
return res;
}