-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
24 lines (24 loc) · 817 Bytes
/
index.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
module.exports = function(movements, array) {
const length = array.length
const result = new Array(array.length)
const toPositions = new Set(movements.values())
if (movements.size !== toPositions.size) {
throw new Error('first parameter must have movements to distinct positions')
}
let fromPosition = 0
let toPosition = 0
while (toPosition < length || fromPosition < length) {
if (movements.has(fromPosition)) {
const to = movements.get(fromPosition)
result[to] = array[fromPosition]
++fromPosition
} else if (toPositions.has(toPosition)) {
++toPosition
} else {
result[toPosition] = array[fromPosition]
++fromPosition
++toPosition
}
}
return result
}