@scale-codec/enum
Version:
Simple JavaScript abstraction around Rust Enums
52 lines (50 loc) • 1.66 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// tsc-build/enum/src/lib.js
var lib_exports = {};
__export(lib_exports, {
variant: () => variant
});
module.exports = __toCommonJS(lib_exports);
var variant = (...args) => new VariantImpl(...args);
var VariantImpl = class {
tag;
__c;
constructor(...args) {
this.tag = args[0];
this.__c = args.length > 1 ? [args[1]] : null;
}
get unit() {
return !this.__c;
}
get content() {
return this.__c?.[0] ?? void 0;
}
as(tag) {
if (this.tag !== tag)
throw new Error(`Cannot cast enum variant "${this.tag}${this.unit ? "" : `(${String(this.content)})`}" as "${tag}"`);
if (this.unit)
throw new Error(`Cannot cast enum variant "${this.tag}" to its content because it is unit`);
return this.content;
}
toJSON() {
const { tag, content, unit } = this;
return unit ? { tag } : { tag, content };
}
};