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

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

问题描述

有谁知道在 TypeScript 中像 GUID (UUID) 这样的 C# 的良好、可靠的实现吗?

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天全站免登陆