Skip to content

Instantly share code, notes, and snippets.

@oampo
Last active December 20, 2016 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oampo/f4d825c9807a38e0779e13a30a3f22a8 to your computer and use it in GitHub Desktop.
Save oampo/f4d825c9807a38e0779e13a30a3f22a8 to your computer and use it in GitHub Desktop.

Higher-order function drills

Functions as arguments

  • Create a function called repeat which takes two arguments:
    • The first argument should be an arbitrary function, fn
    • The second argument should be a number, n
  • repeat should loop n times
  • Each iteration of the loop, it should call fn
  • Create two more functions called hello and goodbye:
    • hello should log the string 'Hello world'
    • goodbye should log the string 'Goodbye world'
  • Use your repeat function to call the hello function five times: repeat(hello, 5)
  • Use your repeat function to call the goodbye function five times: repeat(goodbye, 5)

Functions as return values

  • Create a function called createGreeter which takes a single string argument, greeting

  • createGreeter should return a function

  • The function which is returned should take a single argument, name

  • The function which is returned should log the greeting and name combined. So if greeting was 'Bonjour', and name was 'Sofia' the function should log 'Bonjour Sofia'.

  • Create a "Hello" greeter by calling the createGreeter function, passing 'Hello' as the greeting argument.

  • Create a "Bonjour" greeter by calling the createGreeter function, passing 'Bonjour' as the greeting argument

  • Call your two greeters, passing the names 'Anna' and 'Sofia' as the name argument. Your output should be:

    Hello Anna
    Bonjour Sofia
    

forEach, filter and map

  • A turtle's movements can be represented by an array which looks like this: [3, 4]. The first item in the array represents the number of steps the turtle takes forwards. The second number in the array is the number of steps the turtle takes to the left.
  • Here is an array of different movements made by a turtle: [[0, 0], [0, 5], [-1, -3], [-3, 1], [2, -4], [3, 2]].
  • Use the filter method to remove any items where the turtle moves backwards or to the right (i.e. where either the first of second number is an item is negative).
  • Use the map method to create a new array containing how many steps the turtle makes in total with each movement (i.e. the first and second number added together).
  • Use the forEach method to log out how many steps the turtle took in each case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment