Implement first simple version of sortMoveOperations

This commit is contained in:
Jos de Jong 2020-08-23 18:12:07 +02:00
parent a848358815
commit dff1fc0811
2 changed files with 64 additions and 3 deletions

View File

@ -56,3 +56,37 @@ export function sortObjectKeys (object, direction = 1) {
return sortedObject 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
}

View File

@ -1,7 +1,7 @@
import assert from 'assert' import assert from 'assert'
import { sortArray, sortObjectKeys } from './sort.js' import { sortArray, sortObjectKeys, sortMoveOperations } from './sort.js'
describe('sort', () => { describe.only('sort', () => {
it('should sort array', () => { it('should sort array', () => {
assert.deepStrictEqual(sortArray([ 2, 3, 1 ]), [1, 2, 3]) assert.deepStrictEqual(sortArray([ 2, 3, 1 ]), [1, 2, 3])
@ -31,4 +31,31 @@ describe('sort', () => {
assert.deepStrictEqual(Object.keys(sortObjectKeys(object, -1)), ['c', 'b', 'a']) 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 }
])
})
}) })