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

Commit f035900

Browse files
turisapKent C. Dodds
authored and
Kent C. Dodds
committed
feat: add swapElements function (#153)
* feat(*): add swapElements function this is a completely new feature, swapElements swaps two elements at a given array at specified indexes * * style(*): ESlint corrections Corrections in code as removing semicolons, changing line breaks from CRLF to LF, adding whitespaces
1 parent d09db9d commit f035900

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

src/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import find from './find'
5353
import median from './array-median'
5454
import timeDifference from './timeDifference'
5555
import isPrime from './is-prime'
56+
import swapElements from './swapElements'
5657

5758
export {
5859
isOdd,
@@ -110,4 +111,5 @@ export {
110111
median,
111112
timeDifference,
112113
isPrime,
114+
swapElements,
113115
}

src/swapElements.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Created by HP on 3/1/2018.
3+
*/
4+
export default swapElements
5+
6+
7+
/**
8+
* Original source https://stackoverflow.com/questions/872310/javascript-swap-array-elements
9+
*
10+
* This function swaps elements at indexes 'a' and 'b' in array 'target'
11+
*
12+
* @param {Number} x - the first index in the array 'target'
13+
* @param {Number} y - the second index in the array 'target'
14+
* @param {Array} list - targeted array
15+
*/
16+
function swapElements(x, y, list) {
17+
const b = list[y]
18+
list[y] = list[x]
19+
list[x] = b
20+
}

test/swapElements.test.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* Created by HP on 3/1/2018.
3+
*/
4+
import test from 'ava';
5+
import {swapElements} from '../src';
6+
7+
test('should swap two elements at given indexes in the targeted array', t => {
8+
const target = [1,2,3];
9+
swapElements(1,2,target);
10+
t.deepEqual(target, [1,3,2]);
11+
});

0 commit comments

Comments
 (0)