Last active
January 17, 2017 14:14
-
-
Save michalstocki/410c1d1467bae4b38a2c5ad1427bc172 to your computer and use it in GitHub Desktop.
Remove from string chars at indexes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function removeCharsAtIndexes(inputString:string, indexes:number[]):string { | |
return indexes.reduce((sourceString:string, indexToRemove:number, currentIndex:number) => { | |
return sourceString.slice(0, indexToRemove - currentIndex) + sourceString.slice(indexToRemove - currentIndex + 1); | |
}, inputString); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('removeCharsAtIndexes', () => { | |
describe('removes characters from the given string according to an array containing indexes to be removed,' + | |
'assuming that the given indexes are sorted', () => { | |
[ | |
{ | |
input: 'some string', | |
indexes: [1, 2, 3], | |
caseName: 'subsequent chars from the middle of the string', | |
expectedOutput: 's string' | |
}, | |
{ | |
input: 'some string', | |
indexes: [0], | |
caseName: 'char at the beginning of the string', | |
expectedOutput: 'ome string' | |
}, | |
{ | |
input: 'some string', | |
indexes: [10], | |
caseName: 'char at the end of the string', | |
expectedOutput: 'some strin' | |
}, | |
{ | |
input: 'some string', | |
indexes: [0, 7, 10, 11, 15, 18], | |
caseName: 'chars even if there are extra indexes in the given array', | |
expectedOutput: 'ome stin' | |
} | |
].forEach((stringCase) => { | |
it(`correctly removes ${stringCase.caseName}`, () => { | |
removeCharsAtIndexes(stringCase.input, stringCase.indexes).should.equal(stringCase.expectedOutput); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment