Skip to content

Instantly share code, notes, and snippets.

@dignifiedquire
Last active August 29, 2015 14:04
Show Gist options
  • Save dignifiedquire/c6be2457afa6b41d5c50 to your computer and use it in GitHub Desktop.
Save dignifiedquire/c6be2457afa6b41d5c50 to your computer and use it in GitHub Desktop.
TypeScript Patternmatching
// Translation of functions.ts using sparkler
// https://github.com/natefaubion/sparkler
function pickCard(x) {
[...{ suit @ String, card @ number }] => {
var pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
x @ Number => {
var pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
// Pattern matching on functions
function pickCard {
(x: {suit: string; card: number; }[]): number {
var pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
(x: number): {suit: string; card: number; } {
var pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
// Pattern matching using match translated
function whoami (x) {
match x {
case { name @ String, type: 'person' }:
return 'Person: ' + name;
case { name @ String, type: 'animal' }:
return 'Animal: ' + name;
default:
return 'Unkown you';
}
}
// Pattern matching using match
function whoami (x: any): string {
match x {
case { name: string, type: 'person' }:
return 'Person: ' + name;
case { name: string, type: 'animal' }:
return 'Animal: ' + name;
default:
return 'Unkown you';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment