Skip to content

Instantly share code, notes, and snippets.

@michalstocki
Last active January 17, 2017 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalstocki/410c1d1467bae4b38a2c5ad1427bc172 to your computer and use it in GitHub Desktop.
Save michalstocki/410c1d1467bae4b38a2c5ad1427bc172 to your computer and use it in GitHub Desktop.
Remove from string chars at indexes
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);
}
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