From 651305e8ce2014e44b791d2a0af5c865f76cd037 Mon Sep 17 00:00:00 2001 From: neverland Date: Wed, 23 Mar 2022 22:09:48 +0800 Subject: [PATCH] feat(NumberKeyboard): improve shuffle algorithm (#10428) --- packages/vant/src/number-keyboard/NumberKeyboard.tsx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/vant/src/number-keyboard/NumberKeyboard.tsx b/packages/vant/src/number-keyboard/NumberKeyboard.tsx index 91e86f6ab..94c92d4b7 100644 --- a/packages/vant/src/number-keyboard/NumberKeyboard.tsx +++ b/packages/vant/src/number-keyboard/NumberKeyboard.tsx @@ -65,6 +65,16 @@ const numberKeyboardProps = { export type NumberKeyboardProps = ExtractPropTypes; +function shuffle(array: unknown[]) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + return array; +} + export default defineComponent({ name, @@ -89,7 +99,7 @@ export default defineComponent({ .map((_, i) => ({ text: i + 1 })); if (props.randomKeyOrder) { - keys.sort(() => (Math.random() > 0.5 ? 1 : -1)); + shuffle(keys); } return keys;