util: generateRandomString func

Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
This commit is contained in:
CrazyMax
2024-04-26 13:54:45 +02:00
parent a459c7c911
commit 62e3923775
2 changed files with 21 additions and 0 deletions

View File

@@ -335,6 +335,22 @@ describe('formatFileSize', () => {
});
});
describe('generateRandomString', () => {
it('should generate a random string of default length 10', async () => {
const res = Util.generateRandomString();
expect(typeof res).toBe('string');
expect(res.length).toBe(10);
expect(/^[0-9a-f]+$/i.test(res)).toBe(true);
});
it('should generate a random string of specified length', async () => {
const length = 15;
const res = Util.generateRandomString(length);
expect(typeof res).toBe('string');
expect(res.length).toBe(15);
expect(/^[0-9a-f]+$/i.test(res)).toBe(true);
});
});
// See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89
function getInputName(name: string): string {
return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`;

View File

@@ -174,4 +174,9 @@ export class Util {
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
public static generateRandomString(length = 10) {
const bytes = crypto.randomBytes(Math.ceil(length / 2));
return bytes.toString('hex').slice(0, length);
}
}