perf: keys containing numbers are sorted by size first (#198)

This commit is contained in:
Lykin 2024-03-25 14:57:10 +08:00
parent d99a397ae3
commit 41d0dc6ffc
1 changed files with 43 additions and 5 deletions

View File

@ -1,4 +1,4 @@
import { isEmpty, remove, size, sortedIndexBy, sumBy } from 'lodash' import { isEmpty, remove, size, sumBy } from 'lodash'
import { ConnectionType } from '@/consts/connection_type.js' import { ConnectionType } from '@/consts/connection_type.js'
/** /**
@ -68,6 +68,46 @@ export class RedisNodeItem {
}) })
} }
/**
* compare two items to determine the sort order
* @param {*} a
* @param {*} b
* @return {number}
*/
_sortingCompare(a, b) {
if (a.type !== b.type) {
return a.type - b.type
}
const isANum = isNaN(a.label)
const isBNum = isNaN(b.label)
if (!isANum && !isBNum) {
return parseInt(a.label, 10) - parseInt(b.label, 10)
} else if (!isANum) {
return -1
} else if (!isBNum) {
return 1
}
return a.label.localeCompare(b.label)
}
/**
* calculate insert sorted index
* @param {[]} arr
* @param {*} item
* @return {number}
*/
_sortedIndex(arr, item) {
for (let i = 0; i < arr.length; i++) {
const cmpResult = this._sortingCompare(arr[i], item)
if (cmpResult > 0) {
return i
} else if (cmpResult === 0) {
return i + 1
}
}
return arr.length
}
/** /**
* sort all node item's children and calculate keys count * sort all node item's children and calculate keys count
* @param skipSort skip sorting children * @param skipSort skip sorting children
@ -98,9 +138,7 @@ export class RedisNodeItem {
} }
sortChildren() { sortChildren() {
this.children.sort((a, b) => { this.children.sort(this._sortingCompare)
return a.key > b.key ? 1 : -1
})
} }
/** /**
@ -112,7 +150,7 @@ export class RedisNodeItem {
if (!!!sorted) { if (!!!sorted) {
this.children.push(child) this.children.push(child)
} else { } else {
const idx = sortedIndexBy(this.children, child, 'key') const idx = this._sortedIndex(this.children, child)
this.children.splice(idx, 0, child) this.children.splice(idx, 0, child)
} }
} }