Enum

Enumeration class. Each enum propertiy has the properties "ordinal", "name" and "text".

当前为 2019-11-04 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/391854/746645/Enum.js

  1. // ==UserScript==
  2. // @name Enum
  3. // @namespace hoehleg.userscripts.private
  4. // @version 0.3
  5. // @description Enumeration class. Each enum propertiy has the properties "ordinal", "name" and "text".
  6. // @author Gerrit Höhle
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. /* jslint esnext: true */
  11. const Enum = (() => {
  12. const initializing = Symbol("initializing");
  13.  
  14. return class EnumBase {
  15.  
  16. constructor(processIndicator, { name, ordinal, text } = {}) {
  17. if (processIndicator !== initializing) {
  18. throw TypeError("Instantiation of abstract enum class");
  19. }
  20.  
  21. if (typeof text !== "undefined") {
  22. text = String(text);
  23. }
  24.  
  25. Object.assign(this, {
  26. get ordinal() { return ordinal; },
  27. get name() { return name; },
  28. get text() { return text; }
  29. });
  30. }
  31.  
  32. valueOf() {
  33. return this.ordinal;
  34. }
  35.  
  36. toString() {
  37. return (typeof this.text === "undefined") ? this.name : this.text;
  38. }
  39.  
  40. static init(enumDef = [], firstOrdinal = 0, ordinalSupplier = previousOrdinal => previousOrdinal + 1) {
  41. if (Object.isFrozen(this)) {
  42. throw TypeError("Reinitialization of finalized enum class");
  43. }
  44.  
  45. let ordinal;
  46. const ordinals = [];
  47. for (let enumDefObj of (Array.isArray(enumDef) ? enumDef : [ enumDef ])) {
  48. if (typeof enumDefObj !== 'object') {
  49. enumDefObj = { [enumDefObj]: undefined };
  50.  
  51. }
  52. for (let [name, text] of Object.entries(enumDefObj)) {
  53. ordinal = Number.parseInt((typeof ordinal === "undefined") ? firstOrdinal : ordinalSupplier(ordinal));
  54. console.assert(typeof this[name] === "undefined", `duplicate enum [${name}]`);
  55. console.assert(typeof this[ordinal] === "undefined", `duplicate ordinal [${ordinal}] for enum [${name}]`);
  56.  
  57. this[name] = new this(initializing, { ordinal, name, text });
  58. Object.defineProperty(this, ordinal, {
  59. value: this[name]
  60. });
  61. ordinals.push(ordinal);
  62. }
  63. }
  64.  
  65. const enums = ordinals.sort().map(ordinal => this[ordinal]);
  66. Object.defineProperty(this, Symbol.iterator, { value: () => enums[Symbol.iterator]() });
  67.  
  68. return Object.freeze(this);
  69. }
  70. };
  71. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址