Даяна обнови решението на 07.11.2018 12:39 (преди 9 месеца)
+package main
+
+import "fmt"
+
+var origin []byte
+var add []byte
+var result []byte
+
+type Editor interface {
+
+ // Insert text starting from given position.
+ Insert(position uint, text string) Editor
+
+ // Delete length items from offset.
+ Delete(offset, length uint) Editor
+
+ // Undo reverts latest change.
+ Undo() Editor
+
+ // Redo re-applies latest undone change.
+ Redo() Editor
+
+ // String returns complete representation of what a file looks
+ // like after all manipulations.
+ String() string
+}
+
+type EditorsOrigin struct {
+ origin bool
+ offset int
+ length int
+}
+
+func NewEditor(m string) EditorsOrigin {
+
+ origin = []byte(m)
+ result = []byte(m)
+ add = nil
+
+ return EditorsOrigin{origin: true, offset: 0, length: len(m)}
+}
+
+func (ed EditorsOrigin) Insert(position uint, text string) EditorsOrigin {
+
+ result = make([]byte, 0, len(origin)+len(text))
+ add = []byte(text)
+
+ if len(text) > cap(add) {
+ add = make([]byte, 0, cap(add)*2)
+ add = append(add, add[:]...)
+ }
+
+ if int(position) > cap(result) {
+ result = append(result, origin[:]...)
+ result = append(result, []byte(text)...)
+ } else {
+ result = append(result, origin[:position]...)
+ result = append(result, []byte(text)...)
+ result = append(result, origin[position:]...)
+ }
+
+ return EditorsOrigin{origin: false, offset: int(position), length: len(text)}
+
+}
+
+func (ed EditorsOrigin) Delete(offset, length uint) EditorsOrigin {
+
+ if int(offset) > cap(result) {
+
+ } else if int(length) > cap(result) {
+ result = result[:offset]
+ } else {
+ result = append(result[:offset], result[offset+length:]...)
+
+ }
+ return EditorsOrigin{origin: false, offset: len(origin), length: len(origin) - int(length)}
+
+}
+
+func (ed EditorsOrigin) Undo() EditorsOrigin {
+
+ return EditorsOrigin{origin: false, offset: len(origin), length: len(origin)}
+}
+
+func (ed EditorsOrigin) Redo() EditorsOrigin {
+
+ return EditorsOrigin{origin: false, offset: len(origin), length: len(origin)}
+}
+
+func (ed EditorsOrigin) String() string {
+ fmt.Println(string(result))
+ return fmt.Sprintf(string(result))
+
+}