-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Closed
Labels
Out of ScopeThis idea sits outside of the TypeScript language design constraintsThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
I've seen some short notions about pattern matching on code plex, but no serious discussions around it. As I'm a big fan of it, I've written up some small examples on how I think pattern matching could look in TypeScript.
This is by far no complete specification, just some ideas that I want to bring forward and have a little discussion around.
Function Overloading
// 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 };
}
} // 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 };
}
} Match statement
// 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';
}
} // 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';
}
} zxc122333, download13, gneuvill, airtoxin, nripendra and 219 moreGabiGrin, bali182, gorghoa, jan-molak, jonaskello and 68 more
Metadata
Metadata
Assignees
Labels
Out of ScopeThis idea sits outside of the TypeScript language design constraintsThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScriptAn idea for TypeScript