From 3f15c3cce00f7005237e4a79005ccbe3fad545f6 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 12 Nov 2024 14:35:55 +0100 Subject: [PATCH] feat(VnSelect): order data equal salix --- src/components/common/VnSelect.vue | 3 ++ src/utils/dataByOrder.js | 53 ++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/utils/dataByOrder.js diff --git a/src/components/common/VnSelect.vue b/src/components/common/VnSelect.vue index 32dbbd641..4622f1cb0 100644 --- a/src/components/common/VnSelect.vue +++ b/src/components/common/VnSelect.vue @@ -3,6 +3,8 @@ import { ref, toRefs, computed, watch, onMounted, useAttrs } from 'vue'; import { useI18n } from 'vue-i18n'; import FetchData from 'src/components/FetchData.vue'; import { useRequired } from 'src/composables/useRequired'; +import dataByOrder from 'src/utils/dataByOrder'; + const emit = defineEmits(['update:modelValue', 'update:options', 'remove']); const $attrs = useAttrs(); const { t } = useI18n(); @@ -138,6 +140,7 @@ function findKeyInOptions() { } function setOptions(data) { + data = dataByOrder(data, $props.sortBy); myOptions.value = JSON.parse(JSON.stringify(data)); myOptionsOriginal.value = JSON.parse(JSON.stringify(data)); emit('update:options', data); diff --git a/src/utils/dataByOrder.js b/src/utils/dataByOrder.js new file mode 100644 index 000000000..72b55ac11 --- /dev/null +++ b/src/utils/dataByOrder.js @@ -0,0 +1,53 @@ +function orderData(data, order) { + if (typeof order === 'string') order = [order]; + if (Array.isArray(order)) { + let orderComp = []; + + for (let field of order) { + let split = field.split(/\s+/); + orderComp.push({ + field: split[0], + way: split[1] === 'DESC' ? -1 : 1, + }); + } + + return data.sort((a, b) => sortFunc(a, b, orderComp)); + } else if (typeof order === 'function') return data.sort(data); + return data; +} + +function sortFunc(a, b, order) { + for (let i of order) { + let compRes = compareFunc(a[i.field], b[i.field]) * i.way; + if (compRes !== 0) return compRes; + } + + return 0; +} + +function compareFunc(a, b) { + if (a === b) return 0; + let aType = typeof a; + if (aType === typeof b) { + switch (aType) { + case 'string': + return a.localeCompare(b); + case 'number': + return a - b; + case 'boolean': + return a ? 1 : -1; + case 'object': + if (a instanceof Date && b instanceof Date) + return a.getTime() - b.getTime(); + } + } + + if (a === undefined) return -1; + if (b === undefined) return 1; + if (a === null) return -1; + if (b === null) return 1; + + return a > b ? 1 : -1; +} + +export default orderData;