Generic Functions in Excalidraw
Inside of gestures.ts
, in the Excalidraw codebase is a beautiful example of of the concepts we've explored so far.
The sum
function takes in an array and a mapper
function as a
Transcript
0:00 We're inside the Excalidraw project here. I found this beautiful function called sum, which really shows a lot of the basics with generics and how they can be used really effectively. What sum does is it takes in an array and also a mapper function for the array.
0:17 What it does is it basically reduces the array by turning it into a number. It sums up all of the members of the array while you can also provide a custom function to basically get the number out of that. What we can do is we can say -- let's imagine that we have an array here -- "Constant R equals..."
0:37 Let's say we have an array of numbers here. We could say one, two, three, five. Now we could say, "Constant result equals sum, R." Let's say our mapper is to take the item...and this item is inferred as a string here because all of these things are strings. We can say, "Return pass int item."
0:59 What that's going to do is it's going to iterate through all of the pieces here, and reduce them altogether. We're going to get, basically, eight as a number. It doesn't, of course, know that exactly on the literal types. It knows that it returns a number because we can see there that it's returning a number.
1:16 If I were to change this, if I were to add a different member to this array, we would say...let's say we have an object in here which is wow where we have this, then suddenly inside this slot instead of just being string, it would say string or wow number. We could say, let's say, "Wow in item." Then we would say, "Return item.wow."
1:41 Otherwise, we're going to pass the end there. "Must not be a primitive." That's fun. What we would do is we would say, "If type of item equals object and wow in item, then we're good to go." This gives you a really, really strong sense of what's possible with these generic functions.
2:03 There were just tons and tons all throughout this repo and others that I looked at, too. It's a critical part of understanding application code and being able to imagine having this just beautiful function that you can just take to any complicated array and just grab all of the sum of it. Really, really nice.