Skip to content
This repository was archived by the owner on Jan 12, 2023. It is now read-only.

Commit 24b494b

Browse files
author
Kevin Hermawan
committed
feat: adds move
1 parent eb7e152 commit 24b494b

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

README.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,21 @@ console.log(result); // [1, 2, 3, 5]
137137

138138
### Reordering Elements
139139

140+
#### [move](/src/move.ts)
141+
142+
Moves the element at the specified position to the specified position.
143+
144+
```ts
145+
import { move } from 'enhanced-array';
146+
147+
const result = move([1, 2, 3, 4, 5], { index: 0, toIndex: 4 });
148+
console.log(result); // [2, 3, 4, 5, 1]
149+
```
150+
151+
> **Time complexity:**
152+
>
153+
> O(n), where n is the length of the array.
154+
140155
#### [swap](/src/swap.ts)
141156

142157
Exchanges the element at the specified indices of the array.
@@ -145,7 +160,6 @@ Exchanges the element at the specified indices of the array.
145160
import { swap } from 'enhanced-array';
146161

147162
const result = swap([1, 2, 3, 4, 5], { i: 0, j: 4 });
148-
149163
console.log(result); // [5, 2, 3, 4, 1]
150164
```
151165

src/move.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
type MoveArgs = {
2+
index: number;
3+
toIndex: number;
4+
};
5+
6+
export function move<T>(array: T[], args: MoveArgs) {
7+
const { index, toIndex } = args;
8+
const result: T[] = [];
9+
10+
for (let i = 0; i < array.length; i++) {
11+
if (i !== index) {
12+
result.push(array[i]);
13+
}
14+
15+
if (i === toIndex) {
16+
result.push(array[index]);
17+
}
18+
}
19+
20+
return result;
21+
}

test/move.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { describe, expect, it } from 'vitest';
2+
3+
import { move } from '../src/move';
4+
5+
describe('move', () => {
6+
it('moves element correctly', () => {
7+
const result = move([1, 2, 3, 4, 5], { index: 0, toIndex: 4 });
8+
9+
expect(result).to.eql([2, 3, 4, 5, 1]);
10+
});
11+
});

0 commit comments

Comments
 (0)