Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Created September 16, 2022 18:24
Show Gist options
  • Save IvanAdmaers/9f265c5d41294c3d1646161efa15d8a4 to your computer and use it in GitHub Desktop.
Save IvanAdmaers/9f265c5d41294c3d1646161efa15d8a4 to your computer and use it in GitHub Desktop.
sliceByValue
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 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