diff --git a/packages/amis-formula/__tests__/evalute.test.ts b/packages/amis-formula/__tests__/evalute.test.ts index 32d23b1e5..25a7e875f 100644 --- a/packages/amis-formula/__tests__/evalute.test.ts +++ b/packages/amis-formula/__tests__/evalute.test.ts @@ -563,6 +563,11 @@ test('evalute:Math', () => { expect(evaluate('${POW(2, infinity)}', data)).toBe(data.infinity); }); +test('evalute:UUID', () => { + expect(evaluate('${UUID()}', {}).length).toBe(32); + expect(evaluate('${UUID(8)}', {}).length).toBe(8); +}); + test('evalute:namespace', () => { localStorage.setItem('a', '1'); localStorage.setItem('b', '2'); diff --git a/packages/amis-formula/src/doc.md b/packages/amis-formula/src/doc.md index 37b95f335..ea51e564c 100644 --- a/packages/amis-formula/src/doc.md +++ b/packages/amis-formula/src/doc.md @@ -591,6 +591,16 @@ 返回:a.json`。 +### UUID + +用法:`UUID(8)` + + * `length:number` 生成的UUID字符串长度,默认为32位 + +返回:`string` 生成的UUID字符串 + +生成UUID字符串 + ## 日期函数 ### DATE diff --git a/packages/amis-formula/src/doc.ts b/packages/amis-formula/src/doc.ts index 5291b3029..8ad4d61eb 100644 --- a/packages/amis-formula/src/doc.ts +++ b/packages/amis-formula/src/doc.ts @@ -1022,6 +1022,23 @@ export const doc: { }, namespace: '文本函数' }, + { + name: 'UUID', + description: '生成UUID字符串', + example: 'UUID(8)', + params: [ + { + type: 'number', + name: 'length', + description: '生成的UUID字符串长度,默认为32位' + } + ], + returns: { + type: 'string', + description: '生成的UUID字符串' + }, + namespace: '文本函数' + }, { name: 'DATE', description: diff --git a/packages/amis-formula/src/evalutor.ts b/packages/amis-formula/src/evalutor.ts index 92cdc2f67..e44b570c3 100644 --- a/packages/amis-formula/src/evalutor.ts +++ b/packages/amis-formula/src/evalutor.ts @@ -1514,6 +1514,21 @@ export class Evaluator { return text.split(/[\\/]/).pop(); } + /** + * 生成UUID字符串 + * + * @param {number} length - 生成的UUID字符串长度,默认为32位 + * @example UUID() + * @example UUID(8) + * @namespace 文本函数 + * + * @returns {string} 生成的UUID字符串 + */ + fnUUID(length: number = 32) { + const len = Math.min(Math.max(length, 0), 32); + return uuidv4().slice(0, len); + } + // 日期函数 /** @@ -2414,3 +2429,25 @@ export function createObject( return obj; } + +export function createStr() { + return ( + '00000000000000000' + (Math.random() * 0xffffffffffffffff).toString(16) + ).slice(-16); +} + +export function uuidv4() { + const a = createStr(); + const b = createStr(); + return ( + a.slice(0, 8) + + '-' + + a.slice(8, 12) + + '-4' + + a.slice(13) + + '-a' + + b.slice(1, 4) + + '-' + + b.slice(4) + ); +}