Skip to content

Commit

Permalink
Random string as util, test it
Browse files Browse the repository at this point in the history
  • Loading branch information
arildm committed Sep 20, 2023
1 parent ccdaefa commit 56c9841
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/message/messenger.composable.js
Original file line number Diff line number Diff line change
@@ -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",
});
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
10 changes: 10 additions & 0 deletions src/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
formatDate,
formatSeconds,
pathJoin,
randomString,
setKeys,
} from "./util";

Expand Down Expand Up @@ -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([]);
});
});

0 comments on commit 56c9841

Please sign in to comment.