简体   繁体   中英

Implement a higher-order function called `processLastItem`

I'm working on homework and I'm completely lost.
This is the question:

Implement a higher-order function called processLastItem . It takes two arguments:

  • @param stringList array of strings.
  • @param callback function that takes a string as its argument.
  • @returns the result of invoking callback with the LAST element in stringList ."

They're throwing this at us without having taught it yet so I have no idea where to even start, can someone show me at least where to begin?

A higher order function is basically a function that either returns another function as its result, or takes in a function as a parameter. Here's an example of an implementation of forEach , which is a higher order function. This is pretty useless for actual production code, but hopefully illustrates the concept:

function forEach(array, callbackFunction) {
    for (const item of array) {
        // note we are now calling the passed in function
        callbackFunction(item);
    }
}

So what you need to do with your homework is take this example and pair that together with code to get the last element of an array. Hopefully that shouldn't be as hard with a clear example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM