Created
September 16, 2022 18:24
-
-
Save IvanAdmaers/9f265c5d41294c3d1646161efa15d8a4 to your computer and use it in GitHub Desktop.
sliceByValue
This file contains hidden or 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
import { sliceByValue } from './sliceByValue'; | |
const array = [false, false, true, false, false, false]; | |
describe('sliceByValue', () => { | |
it('should slice by a boolean type value', () => { | |
expect(sliceByValue(array, true)).toEqual([false, false, false]); | |
}); | |
it('should slice by a boolean type value when its the last element', () => { | |
expect(sliceByValue(array, false)).toEqual([]); | |
}); | |
it('should not modify array when an index does not exist', () => { | |
const testArray = [...array, 'hi']; | |
expect(sliceByValue(testArray, 'some value')).toEqual(testArray); | |
}); | |
}); |
This file contains hidden or 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
/** | |
* This function slies array by a value | |
* ([false, true, false], true) => [false] | |
*/ | |
export const sliceByValue = <T>(array: T[], value: T) => { | |
const initialArray = [...array]; | |
const index = initialArray.lastIndexOf(value); | |
if (index === -1) { | |
return initialArray; | |
} | |
return initialArray.slice(index + 1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment