Commit dc1523a3 authored by Ezekiel Kigbo's avatar Ezekiel Kigbo Committed by Mark Florian

Moves `swapArrayItems` to array utilities

Adds an immutable array item swap method
and adds an array_utility file
parent e35cc79a
/**
* Return a shallow copy of an array with two items swapped.
*
* @param {Array} array - The source array
* @param {Number} leftIndex - Index of the first item
* @param {Number} rightIndex - Index of the second item
* @returns {Array} new array with the left and right items swapped
*/
export const swapArrayItems = (array, leftIndex = 0, rightIndex = 0) => {
const copy = array.slice();
if (leftIndex >= array.length || leftIndex < 0 || rightIndex >= array.length || rightIndex < 0) {
return copy;
}
const temp = copy[leftIndex];
copy[leftIndex] = copy[rightIndex];
copy[rightIndex] = temp;
return copy;
};
......@@ -3,6 +3,7 @@ import Vue from 'vue';
import { GlButton, GlForm, GlFormInput, GlFormGroup, GlFormRadioGroup, GlModal } from '@gitlab/ui';
import { mapState, mapActions } from 'vuex';
import { sprintf } from '~/locale';
import { swapArrayItems } from '~/lib/utils/array_utility';
import {
DEFAULT_STAGE_CONFIG,
STAGE_SORT_DIRECTION,
......@@ -15,13 +16,6 @@ import { validateValueStreamName, validateStage } from './create_value_stream_fo
import DefaultStageFields from './create_value_stream_form/default_stage_fields.vue';
import CustomStageFields from './create_value_stream_form/custom_stage_fields.vue';
const swapArrayItems = (arr, left, right) => [
...arr.slice(0, left),
arr[right],
arr[left],
...arr.slice(right + 1, arr.length),
];
const findStageIndexByName = (stages, target = '') =>
stages.findIndex(({ name }) => name === target);
......
import * as arrayUtils from '~/lib/utils/array_utility';
describe('array_utility', () => {
describe('swapArrayItems', () => {
it.each`
array | leftIndex | rightIndex | result
${[]} | ${0} | ${0} | ${[]}
${[1]} | ${0} | ${1} | ${[1]}
${[1, 2]} | ${0} | ${0} | ${[1, 2]}
${[1, 2]} | ${0} | ${1} | ${[2, 1]}
${[1, 2]} | ${1} | ${2} | ${[1, 2]}
${[1, 2]} | ${2} | ${1} | ${[1, 2]}
${[1, 2]} | ${1} | ${10} | ${[1, 2]}
${[1, 2]} | ${10} | ${1} | ${[1, 2]}
${[1, 2]} | ${1} | ${-1} | ${[1, 2]}
${[1, 2]} | ${-1} | ${1} | ${[1, 2]}
${[1, 2, 3]} | ${1} | ${1} | ${[1, 2, 3]}
${[1, 2, 3]} | ${0} | ${2} | ${[3, 2, 1]}
${[1, 2, 3, 4]} | ${0} | ${2} | ${[3, 2, 1, 4]}
${[1, 2, 3, 4, 5]} | ${0} | ${4} | ${[5, 2, 3, 4, 1]}
${[1, 2, 3, 4, 5]} | ${1} | ${2} | ${[1, 3, 2, 4, 5]}
${[1, 2, 3, 4, 5]} | ${2} | ${1} | ${[1, 3, 2, 4, 5]}
`(
'given $array with index $leftIndex and $rightIndex will return $result',
({ array, leftIndex, rightIndex, result }) => {
const actual = arrayUtils.swapArrayItems(array, leftIndex, rightIndex);
expect(actual).toEqual(result);
expect(actual).not.toBe(array);
},
);
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment