Enum

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

目前為 2019-11-03 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/391854/746197/Enum.js

  1. // ==UserScript==
  2. // @name Enum
  3. // @namespace hoehleg.userscripts.private
  4. // @version 0.2
  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. const createEnumInstance = (enumClass, name, ordinal, text = "") => {
  15. text = String(text);
  16. return Object.assign(new enumClass(initializing), {
  17. get ordinal() { return ordinal; },
  18. get name() { return name; },
  19. get text() { return text; },
  20. });
  21. };
  22.  
  23. return class EnumBase {
  24.  
  25. constructor(processIndicator) {
  26. if (processIndicator !== initializing) {
  27. throw TypeError("Instantiation of abstract enum class");
  28. }
  29. }
  30.  
  31. valueOf() { return this.ordinal; }
  32.  
  33. toString() { return this.text || this.name; }
  34.  
  35. static init(enumDef = [], firstOrdinal = 0, ordinalSupplier = previousOrdinal => previousOrdinal + 1) {
  36. if (Object.isFrozen(this)) {
  37. throw TypeError("Reinitialization of finalized enum class");
  38. }
  39.  
  40. let ordinal;
  41. const ordinals = [];
  42. for (let enumDefObj of (Array.isArray(enumDef) ? enumDef : [ enumDef ])) {
  43. if (typeof enumDefObj !== 'object') {
  44. enumDefObj = { [enumDefObj]: "" };
  45.  
  46. }
  47. for (let [name, text] of Object.entries(enumDefObj)) {
  48. ordinal = Number.parseInt((typeof ordinal === "undefined") ? firstOrdinal : ordinalSupplier(ordinal));
  49. console.assert(typeof this[name] === "undefined", `duplicate enum [${name}]`);
  50. console.assert(typeof this[ordinal] === "undefined", `duplicate ordinal [${ordinal}] for enum [${name}]`);
  51.  
  52. ordinals.push(ordinal);
  53.  
  54. this[name] = createEnumInstance(this, name, ordinal, text);
  55. Object.defineProperty(this, ordinal, { value: this[name] });
  56. }
  57. }
  58.  
  59. const enums = ordinals.sort().map(ordinal => this[ordinal]);
  60. Object.defineProperty(this, Symbol.iterator, { value: () => enums[Symbol.iterator]() });
  61.  
  62. return Object.freeze(this);
  63. }
  64. };
  65. })();