11// @flow
22
3- const isEmptyAtPosition = ( word : string , position : number ) => word [ position ] === ' ' || word [ position ] === '\n'
3+ const isEmptyAtPosition = ( word : string , position : number ) => word [ position ] === ' '
44
55export const getWordStartAndEndLocation = ( word : string , position : number ) => {
66 if ( isEmptyAtPosition ( word , position ) && isEmptyAtPosition ( word , position - 1 ) ) {
@@ -19,7 +19,7 @@ export const getWordStartAndEndLocation = (word: string, position: number) => {
1919 ]
2020}
2121
22- export const insertSymbol = ( word : string , position : number , [ prefix , suffix ] : Array < string > ) => {
22+ const insertSymbolInWord = ( word : string , position : number , [ prefix , suffix ] : Array < string > ) => {
2323 const [ start , end ] = getWordStartAndEndLocation ( word , position )
2424 const startWord = word . slice ( 0 , start )
2525 const actualWord = word . slice ( start , end )
@@ -33,3 +33,22 @@ export const insertSymbol = (word: string, position: number, [prefix, suffix]: A
3333 return [ `${ startWord } ${ prefix } ${ actualWord } ${ suffix } ${ endWord } ` , true ]
3434}
3535
36+ // reduce helper
37+ function sum ( total , num ) {
38+ return total + num
39+ }
40+
41+ export const insertSymbol = ( text : string , position : number , [ prefix , suffix ] : Array < string > ) => {
42+ const lines = text . split ( '\n' )
43+ const lineLengths = lines . map ( line => line . length )
44+
45+ const currentLine = text . substring ( 0 , position ) . split ( '\n' ) . length - 1
46+
47+ const relativeLinePosition : number = position - lineLengths . slice ( 0 , currentLine ) . reduce ( sum , 0 )
48+ const [ newLine , replaced ] =
49+ insertSymbolInWord ( lines [ currentLine ] , relativeLinePosition , [ prefix , suffix ] )
50+
51+ lines [ currentLine ] = newLine
52+ return [ lines . join ( '\n' ) , replaced ]
53+ }
54+
0 commit comments