Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 71bf046

Browse files
jlkiriKent C. Dodds
authored and
Kent C. Dodds
committed
feat(reverseArrayInPlace): add reverseArrayInPlace function with tests (#169)
1 parent 3559862 commit 71bf046

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

src/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import reverseArrayInPlace from './reverseArrayInPlace'
12
import isEven from './is-even'
23
import capitalizeFirstLetter from './convert-first-letter-to-capital'
34
import revstring from './revstring'
@@ -61,6 +62,7 @@ import removeAccents from './remove-accents'
6162
import getQueryStringValue from './get-query-string-value'
6263

6364
export {
65+
reverseArrayInPlace,
6466
isOdd,
6567
capitalizeFirstLetter,
6668
isEven,

src/reverseArrayInPlace.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
export default reverseArrayInPlace
2+
3+
/**
4+
* Original Source: https://stackoverflow.com/a/41387918
5+
*
6+
* Function that reverses an array without creating a placeholder array.
7+
*
8+
* @param {Array} array - An array
9+
* @return {Array} - A reversed array
10+
*/
11+
12+
function reverseArrayInPlace(array) {
13+
for (let i = 0; i < Math.floor(array.length / 2); i++) {
14+
const old = array[i]
15+
array[i] = array[array.length - 1 - i]
16+
array[array.length - 1 - i] = old
17+
}
18+
return array
19+
}

test/reverseArrayInPlace.test.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import test from 'ava'
2+
import {reverseArrayInPlace} from '../src'
3+
4+
test('Reverses an array in place', t => {
5+
const array = [1, 2, 3, 4, 5]
6+
const expected = [5, 4, 3, 2, 1]
7+
const actual = reverseArrayInPlace(array)
8+
t.deepEqual(actual, expected)
9+
})
10+
11+
test('Reverses an empty array', t => {
12+
const array = []
13+
const expected = []
14+
const actual = reverseArrayInPlace(array)
15+
t.deepEqual(actual, expected)
16+
})
17+
18+
test('Reverses an with one item', t => {
19+
const array = [1]
20+
const expected = [1]
21+
const actual = reverseArrayInPlace(array)
22+
t.deepEqual(actual, expected)
23+
})

0 commit comments

Comments
 (0)