From 56c9841a4ae360f9df7e1e6c7092bfa8ae6a050a Mon Sep 17 00:00:00 2001 From: Arild Matsson Date: Wed, 20 Sep 2023 16:14:06 +0200 Subject: [PATCH] Random string as util, test it --- src/message/messenger.composable.js | 8 ++++++-- src/util.js | 3 +++ src/util.test.js | 10 ++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/message/messenger.composable.js b/src/message/messenger.composable.js index 6da5b5b..ca0a57f 100644 --- a/src/message/messenger.composable.js +++ b/src/message/messenger.composable.js @@ -1,14 +1,18 @@ import { ref } from "vue"; import remove from "lodash/remove"; +import { randomString } from "@/util"; const alerts = ref([]); // {key, message, status}[] export default function useMessenger() { function alert(message, status) { if (message && status !== "success") { - const key = Math.random().toString(36); // Add message. - alerts.value.push({ key, message, status: status || "debug" }); + alerts.value.push({ + key: randomString(), + message, + status: status || "debug", + }); } } diff --git a/src/util.js b/src/util.js index 8c7d81d..9528408 100644 --- a/src/util.js +++ b/src/util.js @@ -58,3 +58,6 @@ export function setKeys(obj, keys, defaultValue = null) { return obj; } + +/** Create a random string of around 11 chars in the [0-9a-z] range. */ +export const randomString = () => Math.random().toString(36).slice(2); diff --git a/src/util.test.js b/src/util.test.js index 4c574c2..027a6bc 100644 --- a/src/util.test.js +++ b/src/util.test.js @@ -4,6 +4,7 @@ import { formatDate, formatSeconds, pathJoin, + randomString, setKeys, } from "./util"; @@ -54,3 +55,12 @@ describe("setKeys", () => { expect(a).toEqual({ b: 2, c: 10 }); }); }); + +describe("randomString", () => { + test("1000 samples match [0-9a-z]", () => { + const pattern = new RegExp(/^[0-9a-z]+$/); + const samples = Array.from({ length: 1000 }, () => randomString()); + const fails = samples.filter((s) => !pattern.test(s)); + expect(fails).toEqual([]); + }); +});