Skip to content

Commit

Permalink
improve rotate
Browse files Browse the repository at this point in the history
  • Loading branch information
mo-ba committed Sep 22, 2023
1 parent f45f52d commit 1274644
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
30 changes: 26 additions & 4 deletions spec/core/array/operator/rotate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,29 @@ describe('rotate', () => {
const array = [1, 2, 3, 4, 5];
const fn = rotate(2);
expect(fn(array)).to.eql([3, 4, 5, 1, 2,]);

});
it('should rotate negative', () => {
const array = [1, 2, 3, 4, 5];
const fn = rotate(-2);
expect(fn(array)).to.eql([4, 5, 1, 2, 3,]);
});
it('should rotate negative twice', () => {
const array = [1, 2, 3, 4, 5];
expect(rotate(-2)(array)).to.eql(rotate(-12)(array));
});
it('should rotate another test case', () => {
const array = [1, 2, 3, 4, 5, 6, 7];
expect(rotate(-2)(array)).to.eql([6, 7, 1, 2, 3, 4, 5,]);
expect(rotate(2)(array)).to.eql([3, 4, 5, 6, 7, 1, 2,]);
});
it('should rotate mod length', () => {
const array = [1, 2, 3, 4, 5];
const offset = Math.floor(Math.random() * array.length);
const n = Math.round(Math.random() * 10) - 5;
const fn = rotate(offset);
expect(fn(array)).to.eql(rotate(offset + array.length)(array));
expect(fn(array)).to.eql(rotate(offset - array.length)(array));
expect(fn(array)).to.eql(rotate(offset + array.length * n)(array));
});

it('should rotate negative', () => {
Expand All @@ -17,7 +39,7 @@ describe('rotate', () => {

it('should rotate modulo', () => {
const array = [1, 2, 3, 4, 5];
expect(rotate(6)(array)).to.eql(rotate(6%array.length)(array));
expect(rotate(6)(array)).to.eql(rotate(6 % array.length)(array));

});

Expand All @@ -28,11 +50,11 @@ describe('rotate', () => {

it('should rotate early', () => {
const fn = rotate(2);
expect(fn([1])).to.eql([1,]);
expect(fn([1])).to.eql([1]);
});
it('should rotate last', () => {
const fn = rotate(2);
expect(fn([1, 2])).to.eql([1, 2,]);
expect(fn([1, 2])).to.eql([1, 2]);
});

it('should rotate 0', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/array/operator/rotate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export function rotate(offset: number) {
return <S>(array: S[]): S[] => {
const length = array.length;
const index = ((offset % length) + length) % length;
return <T>(array: T[]): T[] => {
const index = offset % array.length;
return array.slice(index).concat(array.slice(0, index));
};
}
2 changes: 1 addition & 1 deletion src/array/operator/rotateBack.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import {rotate} from './rotate';

export const rotateBack = (offset: number) => rotate(-offset)
export const rotateBack = (offset: number) => rotate(-offset);

0 comments on commit 1274644

Please sign in to comment.