TypeScript GUID类? [英] A TypeScript GUID class?

查看:227
本文介绍了TypeScript GUID类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道TypeScript中良好的,可靠的C#实现,例如GUID(UUID)吗?

Does anyone know of a good, solid, implementation of C# like GUID (UUID) in TypeScript?

我自己可以做,但认为如果别人以前做过,我会花时间.

Could do it myself but figured I'd spare my time if someone else done it before.

推荐答案

我的 TypeScript实用程序中有一个实现基于JavaScript GUID生成器.

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

这是代码:

class Guid {
  static newGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
}

// Example of a bunch of GUIDs
for (var i = 0; i < 100; i++) {
  var id = Guid.newGuid();
  console.log(id);
}

请注意以下几点:

C#GUID保证是唯一的.此解决方案非常有可能是唯一的. 非常可能"和保证"之间存在巨大的差距,您不想跌破这个差距.

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript生成的GUID非常适合用作等待服务器响应时使用的临时键,但是我不一定会相信它们是数据库中的主键.如果您要依靠JavaScript生成的GUID,则每次创建GUID时都会尝试检查一个寄存器,以确保没有重复(某些情况下,Chrome浏览器中会出现此问题) ).

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

这篇关于TypeScript GUID类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆