UNPKG

1.23 kBPlain TextView Raw
1import type { Verification } from "./types";
2
3const DEFAULT_LENGTH = 3;
4
5function includes(array: number[], thing: number): boolean {
6 for (let i = 0; i < array.length; i++) {
7 if (thing === array[i]) {
8 return true;
9 }
10 }
11
12 return false;
13}
14
15function max(array: number[]): number {
16 let maximum = DEFAULT_LENGTH;
17 let i = 0;
18
19 for (; i < array.length; i++) {
20 maximum = array[i] > maximum ? array[i] : maximum;
21 }
22
23 return maximum;
24}
25
26function verification(
27 isValid: boolean,
28 isPotentiallyValid: boolean,
29): Verification {
30 return { isValid, isPotentiallyValid };
31}
32
33export function cvv(
34 value: string | unknown,
35 maxLength: number | number[] = DEFAULT_LENGTH,
36): Verification {
37 maxLength = maxLength instanceof Array ? maxLength : [maxLength];
38
39 if (typeof value !== "string") {
40 return verification(false, false);
41 }
42 if (!/^\d*$/.test(value)) {
43 return verification(false, false);
44 }
45 if (includes(maxLength, value.length)) {
46 return verification(true, true);
47 }
48 if (value.length < Math.min.apply(null, maxLength)) {
49 return verification(false, true);
50 }
51 if (value.length > max(maxLength)) {
52 return verification(false, false);
53 }
54
55 return verification(true, true);
56}