I jump between Java and Javascript a lot at work. I also write a lot of functional code, i.e. chains of lambdas.
One thing I like about Java is I can replace a lambda with a method reference. For example, I can replace this code
List<String> trimmedStrings = List.of("hi ", "bye ").stream()
.map(original -> original.trim())
.collect(toList());
with this:
List<String> trimmedStrings = List.of("hi ", "bye ").stream()
.map(String::trim)
.collect(toList());
I often make this replacement because I'm usually happier with the end state of how the code looks.
I have been wondering if I can do this with Javascript. I just tested this code in my browser console:
["hi ", "bye "].map(original => original.trim());
first I tried replacing it the simple way, which worked but doesn't accomplish my goal:
["hi ", "bye "].map(original => String.prototype.trim.apply(original))
So I figured the following would work, but it didn't:
["hi ", "bye "].map(String.prototype.trim.apply)
it gave me an error saying Uncaught TypeError: Can't call method on undefined
(in Firefox).
So my questions are:
- Why doesn't this work?
- Is there another, better way to do what I want here?