Last active
August 29, 2015 14:12
-
-
Save tetsuharuohzeki/dbc2ce26fa4e3dc9db72 to your computer and use it in GitHub Desktop.
Rustのcore::options::Option<T>のAPIをTypeScriptで再現
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module option { | |
// This interface is based on Rust's `core::option::Option<T>`/ | |
class Option<T> { | |
private _val: T; | |
private _is_some: boolean; | |
constructor(val?: T) { | |
this._val = val; | |
this._is_some = (val !== undefined); | |
} | |
public is_some(): boolean { | |
return this._is_some; | |
} | |
public is_none(): boolean { | |
return !this._is_some; | |
} | |
public unwrap(): T { | |
if (!this._is_some) { | |
throw new Error("cannot unwrapping!"); | |
} | |
return this._val; | |
} | |
public map<U>(fn: (v: T) =>U ): Option<U> { | |
if (!this._is_some) { | |
// cheat to escape from a needless allocation. | |
return <Option<any>>this; | |
} | |
var val: U = fn(this._val); | |
return new Option<U>(val); | |
} | |
public map_or<U>(def: U, fn: (v: T) => U): U { | |
if (!this._is_some) { | |
return fn(this._val); | |
} | |
else { | |
return def; | |
} | |
} | |
public map_or_else<U>(def: ()=>U, fn: (v: T) => U): U { | |
if (this._is_some) { | |
return fn(this._val); | |
} | |
else { | |
return def(); | |
} | |
} | |
public and<U>(b: Option<U>): Option<U> { | |
if (this._is_some) { | |
return b; | |
} | |
else { | |
// cheat to escape from a needless allocation. | |
return <Option<any>>this; | |
} | |
} | |
public and_then<U>(fn: (v: T)=> Option<U>): Option<U> { | |
if (this._is_some) { | |
return fn(this._val); | |
} | |
else { | |
// cheat to escape from a needless allocation. | |
return <Option<any>>this; | |
} | |
} | |
public or(b: Option<T>): Option<T> { | |
if (this._is_some) { | |
return this; | |
} | |
else { | |
return b; | |
} | |
} | |
public or_else(fn: () => Option<T>) { | |
if (this._is_some) { | |
return this; | |
} | |
else { | |
return fn(); | |
} | |
} | |
// Use to release the contained value explicitly. | |
public drop() { | |
this._val = null; | |
this._is_some = false; | |
Object.freeze(this); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment