Implement first simple version of sortMoveOperations
This commit is contained in:
parent
a848358815
commit
dff1fc0811
|
@ -56,3 +56,37 @@ export function sortObjectKeys (object, direction = 1) {
|
|||
|
||||
return sortedObject
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an array containing all move operations
|
||||
* needed to sort the array contents.
|
||||
* @param {Array} array
|
||||
* @param {function (a, b) => number} comparator
|
||||
* @param {Array.<{fromIndex: number, toIndex: number}>}
|
||||
*/
|
||||
export function sortMoveOperations (array, comparator) {
|
||||
const operations = []
|
||||
|
||||
const sorted = array.slice()
|
||||
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
// TODO: implement a faster way to sort (binary tree sort?)
|
||||
// TODO: can we simplify the following code?
|
||||
if (comparator(sorted[i - 1], sorted[i]) > 0) {
|
||||
let j = i - 1
|
||||
while (comparator(sorted[j - 1], sorted[i]) > 0 && j > 0) {
|
||||
j--
|
||||
}
|
||||
|
||||
operations.push({
|
||||
fromIndex: i,
|
||||
toIndex: j
|
||||
})
|
||||
|
||||
const item = sorted.splice(i, 1)
|
||||
sorted.splice(j, 0, [item])
|
||||
}
|
||||
}
|
||||
|
||||
return operations
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
import assert from 'assert'
|
||||
import { sortArray, sortObjectKeys } from './sort.js'
|
||||
import { sortArray, sortObjectKeys, sortMoveOperations } from './sort.js'
|
||||
|
||||
describe.only('sort', () => {
|
||||
|
||||
describe('sort', () => {
|
||||
|
||||
it('should sort array', () => {
|
||||
assert.deepStrictEqual(sortArray([ 2, 3, 1 ]), [1, 2, 3])
|
||||
assert.deepStrictEqual(sortArray([ 2, 3, 1 ], undefined, -1), [3, 2, 1])
|
||||
|
@ -31,4 +31,31 @@ describe('sort', () => {
|
|||
assert.deepStrictEqual(Object.keys(sortObjectKeys(object, -1)), ['c', 'b', 'a'])
|
||||
})
|
||||
|
||||
it('should give the move operations needed to sort given array', () => {
|
||||
const comparator = (a, b) => a - b
|
||||
|
||||
assert.deepStrictEqual(sortMoveOperations([ 1, 2, 3 ], comparator), [])
|
||||
|
||||
assert.deepStrictEqual(sortMoveOperations([ 2, 3, 1 ], comparator), [
|
||||
{ fromIndex: 2, toIndex: 0 }
|
||||
])
|
||||
|
||||
assert.deepStrictEqual(sortMoveOperations([ 2, 1, 3 ], comparator), [
|
||||
{ fromIndex: 1, toIndex: 0 }
|
||||
])
|
||||
|
||||
assert.deepStrictEqual(sortMoveOperations([ 1, 3, 2 ], comparator), [
|
||||
{ fromIndex: 2, toIndex: 1 }
|
||||
])
|
||||
|
||||
assert.deepStrictEqual(sortMoveOperations([ 3, 2, 1 ], comparator), [
|
||||
{ fromIndex: 1, toIndex: 0 },
|
||||
{ fromIndex: 2, toIndex: 0 }
|
||||
])
|
||||
|
||||
assert.deepStrictEqual(sortMoveOperations([ 3, 1, 2 ], comparator), [
|
||||
{ fromIndex: 1, toIndex: 0 },
|
||||
{ fromIndex: 2, toIndex: 1 }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
|
Loading…
Reference in New Issue