Skip to content

Commit

Permalink
fix: duped buckets
Browse files Browse the repository at this point in the history
  • Loading branch information
joscha committed Sep 23, 2024
1 parent b21aee8 commit ad181b6
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions lib/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -1266,29 +1266,38 @@ class UnwrappedUnionType extends UnionType {

this._dynamicBranches = null;
this._bucketIndices = {};

this.projectionFunction = (val) => this._bucketIndices[getValueBucket(val)];
let hasWrapUnionsFn = opts && typeof opts.wrapUnions === 'function';
if (hasWrapUnionsFn) {
const projectionFunction = opts.wrapUnions(this.types);
if (typeof projectionFunction === 'undefined') {
hasWrapUnionsFn = false;
} else {
this.projectionFunction = (val) => {
const index = projectionFunction(val);
if (typeof index !== 'number' || index >= this._bucketIndices.length) {
throw new Error(`Projected index ${index} is not valid`);
}
return index;
}
}
}

this.types.forEach(function (type, index) {
if (Type.isType(type, 'abstract', 'logical')) {
if (!this._dynamicBranches) {
this._dynamicBranches = [];
}
this._dynamicBranches.push({index, type});
} else {
} else if (!hasWrapUnionsFn) {
let bucket = getTypeBucket(type);
if (this._bucketIndices[bucket] !== undefined) {
throw new Error(`ambiguous unwrapped union: ${j(this)}`);
}
this._bucketIndices[bucket] = index;
}
}, this);
this.projectionFunction = opts && typeof opts.wrapUnions === 'function'
? ((fn) => (val) => {
const index = fn(val);
if (typeof index !== 'number' || index >= this._bucketIndices.length) {
throw new Error(`Projected index ${index} is not valid`);
}
return index;
})(opts.wrapUnions(this.types))
: (val) => this._bucketIndices[getValueBucket(val)]

Object.freeze(this);
}
Expand Down

0 comments on commit ad181b6

Please sign in to comment.