Enum

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

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/391854/746956/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 = class EnumBase {
  12.  
  13. constructor({ name, ordinal, text } = {}) {
  14. if (new.target === EnumBase) {
  15. throw TypeError("Instantiation of abstract enum class");
  16. }
  17.  
  18. if (typeof text !== "undefined") {
  19. text = String(text);
  20. }
  21.  
  22. Object.assign(this, {
  23. get ordinal() { return ordinal; },
  24. get name() { return name; },
  25. get text() { return text; }
  26. });
  27. }
  28.  
  29. valueOf() {
  30. return this.ordinal;
  31. }
  32.  
  33. toString() {
  34. return (typeof this.text === "undefined") ? this.name : this.text;
  35. }
  36.  
  37. static init(enumDef = [], firstOrdinal = 0, ordinalSupplier = previousOrdinal => previousOrdinal + 1) {
  38. if (Object.isFrozen(this)) {
  39. throw TypeError("Reinitialization of finalized enum class");
  40. }
  41.  
  42. let ordinal;
  43. const ordinals = [];
  44. for (let enumDefObj of (Array.isArray(enumDef) ? enumDef : [ enumDef ])) {
  45. if (typeof enumDefObj !== 'object') {
  46. enumDefObj = { [enumDefObj]: undefined };
  47. }
  48. for (let [name, text] of Object.entries(enumDefObj)) {
  49. ordinal = Number.parseInt((typeof ordinal === "undefined") ? firstOrdinal : ordinalSupplier(ordinal));
  50. console.assert(typeof this[name] === "undefined", `duplicate enum [${name}]`);
  51. console.assert(typeof this[ordinal] === "undefined", `duplicate ordinal [${ordinal}] for enum [${name}]`);
  52.  
  53. this[name] = new this({ ordinal, name, text });
  54. Object.defineProperty(this, ordinal, {
  55. value: this[name]
  56. });
  57.  
  58. ordinals.push(ordinal);
  59. }
  60. }
  61.  
  62. const enums = ordinals.sort().map(ordinal => this[ordinal]);
  63. Object.defineProperty(this, Symbol.iterator, { value: () => enums[Symbol.iterator]() });
  64.  
  65. return Object.freeze(this);
  66. }
  67. };