hid this if, which i could not dare see
When learning about a new technology and understanding its advantages and ingenuity over what you were previously used to, you kinda feel the urge to use your new super powers all over the place.
A good example for me is the really clever approach the Rust language took with its pattern matching oriented syntax.
1match time_of_day {
2 1..=21 => Some(5),
3 22 ..= 24 => Some(0),
4 _ => None
5}
I mostly write JavaScript for a living but really wanna live in the future already. I'll show you my attempt at it. 🦀
Pattern matching in JS ?
Quick disclaimer, obviously type checking is out of the question right away. So no matching on enum and crazy thing like that.
The most we can do in JS would be to throw a
typeofin the mix, which has some limited results as we know it.
So, let's say we have a basic function like :
1function myFunc(code: number): string {
2 let ret;
3 if(code === 200)
4 ret = 'something';
5 else if(code === 404)
6 ret = 'something else';
7 else if(code === 401)
8 ret = 'also something else';
9 return ret;
10}
Ugly imho.
So let's do that instead
1function myFunc(code: number): string {
2 return {
3 200: 'something',
4 404: 'something else',
5 401: 'also something else'
6 }[code] ?? 'No matching';
7}
The ?? 'No matching' part is the default case.
Why not just Switch statement ?
Yeah why not (also, spoiler: switches are boring)
But I wanted this first example to be an introduction as I will follow the same pattern to create a Match function and to have the fizzBuzz thing working.
1type Pattern<Test extends Function,Value> = [Test,Value];
2
3const Match = <Test extends Function,Value>(target: any, patterns: Array<Pattern<Test,Value>>): Value =>
4 (patterns.filter(pattern => pattern[0](target)) as Array<Pattern<Test,Value>>).map(pattern => pattern[1])
5
6function fizzBuzz(num: number) {
7 return Match(num, [
8 [n => n % 3 == 0, 'fizz'],
9 [n => n % 5 == 0, 'buzz']
10 ]).reduce((prev, curr) => prev += curr);
11}
I know this kinda looks bad, but don't worry I won't make an npm package out of it. 🤓