Skip to content

Instantly share code, notes, and snippets.

@akanehara
Created September 10, 2013 08:27
Show Gist options
  • Save akanehara/6506524 to your computer and use it in GitHub Desktop.
Save akanehara/6506524 to your computer and use it in GitHub Desktop.
interface Decoder<A> {
decode(source: string): A;
}
class NumDecoder implements Decoder<Number> {
decode(source: string): Number {
return Number(source.trim());
}
}
class StringDecoder implements Decoder<string> {
decode(source: string): string {
return source.trim();
}
}
class ListDecoder<A> implements Decoder<A[]> {
constructor(public itemDecoder: Decoder<A>) {}
decode(source: string): A[] {
var ss: string[] = source.split(',');
return ss.map(this.itemDecoder.decode);
}
}
var numDecoder: Decoder<Number> = new NumDecoder();
var strDecoder: Decoder<string> = new StringDecoder();
var numListDecoder: Decoder<Number[]> = new ListDecoder(numDecoder);
alert(String(numDecoder.decode("019")));
alert(strDecoder.decode("hogera"));
alert(String(numListDecoder.decode(" 10 , 20 , 30 ")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment