Writing your own map, reduce, compactMap and more Higher-Order functions
Higher-Order functions; If you have some experience working in swift, you might have used it at several places in your code. A function that takes one or more function as argument is called Higher-Order function.
But here, what I am more interested in explaining is how to write your own Higher-Order function. ( It is hot question for many companies too, so stay tuned ). What I have seen in my experience that this question is put in such a way that it seems complicated when asked, which is not that tricky actually.
Let’s start with this question and answer it;
What is an Higher-Order function?
This you already know if you have reached here.
The above question has a follow-up question too
Write your own map function.
To answer this one you must know what map(_:) actually does.
Map
As Apple Documentation says
Returns an array containing the results of mapping the given closure over the sequence’s elements.
So, we need to pass an operation/function which will be applied on each element of the given Sequence to another function ( i.e. myMap(_ :) our higher-order function) which will return final Sequence with updated values.
Here operation is a “function” that’ll be applied to every element of the given Sequence (simply Array to understand).
Reduce
CompactMap
Filter
Thanks for reading.