naive-ui/packages/utils/data/linkedOptions.js
07akioni 9db4e0edaa refactor(select): imporve perf & api change
1. restrain option value to string & number, for find id by value is a huge overhead when where is too many options.
2. use value as option.id, for the same reason
3. imporve the perf of select by remove some bottle neck function
2019-12-26 01:32:36 +08:00

57 lines
1.4 KiB
JavaScript

/**
* For Select Component to use
* Todo: Refactor to avoid link list, since it will make component intrinsic
* logic more complex
*/
import cloneDeep from 'lodash/cloneDeep'
function markAvailableOptionIds (options) {
const length = options.length
if (length === 0) return
let lastAvailableOption = null
options.firstAvailableOptionId = null
for (let i = 0; i < length; ++i) {
const option = options[i]
if (!option.disabled) {
options.firstAvailableOptionId = option.id
break
}
}
for (let i = 0; i < length; ++i) {
const option = options[i]
option.nextAvailableOptionId = null
option.prevAvailableOptionId = null
}
for (let i = 0; i <= length * 2; ++i) {
const option = options[i % length]
if (lastAvailableOption) {
option.prevAvailableOptionId = lastAvailableOption.id
}
if (!option.disabled) {
lastAvailableOption = option
}
}
lastAvailableOption = null
for (let i = length * 2; i >= 0; --i) {
const option = options[i % length]
if (lastAvailableOption) {
option.nextAvailableOptionId = lastAvailableOption.id
}
if (!option.disabled) {
lastAvailableOption = option
}
}
}
export default function linkedOptions (options) {
const decoratedOptions = cloneDeep(options).map((option) => {
return {
...option,
id: option.value
}
})
markAvailableOptionIds(decoratedOptions)
return decoratedOptions
}