diff --git a/src/index.js b/src/index.js index 2615a722..eae1beb2 100644 --- a/src/index.js +++ b/src/index.js @@ -53,6 +53,7 @@ import find from './find' import median from './array-median' import timeDifference from './timeDifference' import isPrime from './is-prime' +import swapElements from './swapElements' export { isOdd, @@ -110,4 +111,5 @@ export { median, timeDifference, isPrime, + swapElements, } diff --git a/src/swapElements.js b/src/swapElements.js new file mode 100644 index 00000000..1b7413fc --- /dev/null +++ b/src/swapElements.js @@ -0,0 +1,20 @@ +/** + * Created by HP on 3/1/2018. + */ +export default swapElements + + +/** + * Original source https://stackoverflow.com/questions/872310/javascript-swap-array-elements + * + * This function swaps elements at indexes 'a' and 'b' in array 'target' + * + * @param {Number} x - the first index in the array 'target' + * @param {Number} y - the second index in the array 'target' + * @param {Array} list - targeted array + */ +function swapElements(x, y, list) { + const b = list[y] + list[y] = list[x] + list[x] = b +} diff --git a/test/swapElements.test.js b/test/swapElements.test.js new file mode 100644 index 00000000..4ec9e0ad --- /dev/null +++ b/test/swapElements.test.js @@ -0,0 +1,11 @@ +/** + * Created by HP on 3/1/2018. + */ +import test from 'ava'; +import {swapElements} from '../src'; + +test('should swap two elements at given indexes in the targeted array', t => { + const target = [1,2,3]; + swapElements(1,2,target); + t.deepEqual(target, [1,3,2]); +}); \ No newline at end of file