nochoices
Version:
Full featured implementation of options into typescript.
98 lines (97 loc) • 2.03 kB
JavaScript
import { OptionalValue } from "./optional-value.js";
import { Option } from "./option.js";
export class Some extends OptionalValue {
value;
constructor(value) {
super();
this.value = value;
}
isPresent() {
return true;
}
isAbsent() {
return false;
}
unwrap() {
return this.value;
}
map(fn) {
const newValue = fn(this.value);
return Option.Some(newValue);
}
filter(fn) {
const res = fn(this.value);
if (res) {
return Option.Some(this.value);
}
return Option.None();
}
expect(_err) {
return this.value;
}
unwrapOr(_defaultValue) {
return this.value;
}
unwrapOrElse(_defaultFn) {
return this.value;
}
flatten() {
if (this.value instanceof Option) {
return this.value;
}
else {
return Option.Some(this.value);
}
}
zip(another) {
return another.zipWithSome(this);
}
zipWithSome(some) {
return Option.Some([some.value, this.value]);
}
and(another) {
return another;
}
or(self, _another) {
return self;
}
xor(another) {
return another.xorWithSome(this);
}
xorWithNone() {
return Option.Some(this.value);
}
xorWithSome(_some) {
return Option.None();
}
andThen(fn) {
return fn(this.value);
}
orElse(_fn) {
return Option.Some(this.value);
}
getOrInsert(_value) {
return this;
}
getOrInsertWith(_fn) {
return this;
}
takeValue() {
return Option.Some(this.value);
}
isSomeAnd(andFn) {
return andFn(this.value);
}
ifSome(param) {
param(this.value);
}
ifNone(_fn) {
/* no-op */
}
toArray() {
return [this.value];
}
equalsWith(another, equality) {
return another.isSomeAnd(t => equality(this.value, t));
}
}