/
MoveTo.js
41 lines (35 loc) · 1001 Bytes
/
MoveTo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Moves an element in an array to a new position within the same array.
* The array is modified in-place.
*
* @function Phaser.Utils.Array.MoveTo
* @since 3.4.0
*
* @param {array} array - The array.
* @param {*} item - The element to move.
* @param {number} index - The new index that the element will be moved to.
*
* @return {*} The element that was moved.
*/
var MoveTo = function (array, item, index)
{
var currentIndex = array.indexOf(item);
if (currentIndex === -1 || index < 0 || index >= array.length)
{
throw new Error('Supplied index out of bounds');
}
if (currentIndex !== index)
{
// Remove
array.splice(currentIndex, 1);
// Add in new location
array.splice(index, 0, item);
}
return item;
};
module.exports = MoveTo;