Hi folks,
thanks for the work on TC39.
I read the future plans wiki page and also skimmed the closed issues and did not find anything related.
A frequent use case for pattern matching I run into with JS is pattern matching with function arguments.
Example:
function handler (arg1 typeof String, cb typeof Function) {
console.log('string passed') // do some string related handling
cb(null, arg1)
}
function handler (arg1 typeof Object, cb typeof Function) {
console.log('object passed') // do some object related handling
cb(null, arg1)
}
function handler (arg1 typeof String, arg2 typeof String, cb typeof Function) {
console.log('two strings passed') // do some string related handling
cb(null, arg1)
}
handler('foo', () => {}) // logs: 'string passed'
handler({}, () => {}) // logs: 'object passed'
handler('foo', 'foo', () => {}) // logs: 'two strings passed'
handler('foo') // Error: no match
handler('foo', 1) // Error: no match
Was this use case already discussed?
This feels more like Function Overloading than strictly pattern matching.
The example @robertkowalski gave seems like Function Overloading. However, function arguments could take advantage of pattern matching on some other cases:
function sumList([], accumulator) {
return accumulator;
}
function sumList([head, ...tail], accumulator) {
return sumList(tail, head + accumulator);
}
sumList([], 0); // 0
sumList([1, 2], 0): // 3
sumList([1, 2, 3], 0); // 6
This would try every function declaration with the same name (in order) until something matches, and throws if doesn't find a match.
This is useful for many libraries which API includes functions that handles many different number and type of arguments (from the top of my head I can only think of momentjs but I'll keep looking for more examples because IIRC is very common)
Here are some examples of this feature on the Elixir language docs:
yes, i agree. my example was not good.
actually i mean this feature, described in https://learnyousomeerlang.com/syntax-in-functions#pattern-matching:
greet(male, Name) ->
io:format("Hello, Mr. ~s!", [Name]);
greet(female, Name) ->
io:format("Hello, Mrs. ~s!", [Name]);
greet(_, Name) ->
io:format("Hello, ~s!", [Name]).
As a former Erlang person, I really don't think this extension fits that well into JavaScript, and will only increase complexity of functions. I believe it's a micro-optimization to have syntax sugar for this, when you can easily do the following:
function sumList(list, accumulator = 0) {
return case (list) {
let [] => accumulator,
let [head, ...tail] => sumList(tail, head + accumulator)
}
}
Most helpful comment
This feels more like Function Overloading than strictly pattern matching.