Implement Buffer.positionForCharacterIndex

This commit is contained in:
Corey Johnson
2012-03-21 14:40:44 -07:00
parent 0efbd65a24
commit e786bb8055
2 changed files with 19 additions and 1 deletions

View File

@@ -210,4 +210,14 @@ describe 'Buffer', ->
expect(buffer.characterIndexForPosition([0, 1])).toBe 1
expect(buffer.characterIndexForPosition([0, 29])).toBe 29
expect(buffer.characterIndexForPosition([1, 0])).toBe 30
expect(buffer.characterIndexForPosition([2, 0])).toBe 61
expect(buffer.characterIndexForPosition([2, 0])).toBe 61
expect(buffer.characterIndexForPosition([12, 2])).toBe 408
describe ".positionForCharacterIndex(position)", ->
it "returns the position based on charachter index", ->
expect(buffer.positionForCharacterIndex(0)).toEqual [0, 0]
expect(buffer.positionForCharacterIndex(1)).toEqual [0, 1]
expect(buffer.positionForCharacterIndex(29)).toEqual [0, 29]
expect(buffer.positionForCharacterIndex(30)).toEqual [1, 0]
expect(buffer.positionForCharacterIndex(61)).toEqual [2, 0]
expect(buffer.positionForCharacterIndex(408)).toEqual [12, 2]

View File

@@ -67,6 +67,14 @@ class Buffer
index += @getLineLength(row) + 1 for row in [0...position.row]
index + position.column
positionForCharacterIndex: (index) ->
row = 0
while index >= (lineLength = @getLineLength(row) + 1)
index -= lineLength
row++
new Point(row, index)
deleteRow: (row) ->
range = null
if row == @lastRow()