Functional JavaScript Workshop

Tram Ho

https://github.com/timoxley/functional-javascript-workshop

Higher Order Functions

  • A higher Higher-order function is a function that acts on top of other functions, either by taking them as parameters or returning them. simply said a function that takes a function as an argument or returns a function as an output.
  • Unlike many other languages ​​with mandatory features, JavaScript allows you to use higher-order functions more because it has a first-class function . This means that functions can be treated like any other value in JavaScript: like String or Number, Function values ​​can be stored as variables, properties on objects, or passed to other functions as arguments. Function values ​​are actually Objects (inheriting from Function.prototype ) so you can even add properties and store values ​​on them, just like any regular Object.
  • The main difference between Function and other value types in JavaScript is the call syntax: if the reference to a function is followed by parentheses and some value is separated by an optional comma: someFunctionValue(arg1, arg2, etc) , then the function body will be executed with the supplied arguments (if any).
  • We’ll demonstrate that functions can be passed as values ​​by passing you a function as an argument.
    • Example: Implement a function that takes a function as its first argument, a number num as its second argument, and then executes the function passed in num function time.

Basic: Map

  • The map() method creates a new array with the results of calling a given function on each element of this array.
  • Example: Convert code from for loop to Array#map
    • Using for()

    • Using map()

Basic: Filter

  • The filter() method creates a new array filtered down to only the elements from the given array that satisfy the condition performed by the provided function.
  • filter() does not execute the function for empty elements
  • filter() does not change the original array
  • Example: Create a function getShortMessages that takes an array of objects with property ‘ .message ‘ and returns a message less than 50 characters in length. The function returns an array containing the messages without their container object.

Basic: Every Some

  • The every() method checks if all the elements in the array satisfy a certain condition. It returns a Boolean value. If all elements are satisfied, return true , otherwise, if only one element is not satisfied, it will return false .
    • For example

  • The some() method iterates all the elements in an array and as long as one element satisfies the condition, the array will return true .
    • For example

  • Example: Returns a function that takes a list of valid users and returns a function that returns true if all supplied users exist in the original list of users. You just need to check if the ids match. Use Array#some and Array#every to check every user passed to your return function exists in the array passed to the output function.

Basic: Reduce

  • The reduce() method executes a user-provided “reduce” callback on each element of the array, in order, passing the return value from the calculation on the previous element. The end result of running the reducer on all the elements of the array is a single value.
  • Example: Given an Array of Strings, use Array#reduce to create an object containing the number of times each string appears in the array. Return the tuwonngj argument directly (no console.log needed).

Basic: Recursion

  • Recursion is a fundamental programming concept that can lead to elegant and efficient solutions to algorithmic problems. In fact, recursion is so powerful, all repeating behavior can be defined using array recursion . You’ll find recursion indispensable when iterating over nested data structures.
  • Function recursion is a function that calls itself. For example, this recursive function will take an array of words and return an array of those words, capitalized.

  • The purpose of this exercise is to familiarize yourself with recursion by implementing a familiar interface using a recursive function.

Basic: Call

  • The call() method calls the function with a given this value and the arguments provided individually.

  • Pototype is the mechanism for implementing the OOP model of Javascript, where objects inherit the same features. Every object in JavaScript has an internal property called prototype.

  • What is the difference between the 2 ways of object initialization
    • Object.create() is a method that creates a new object, using an existing object as the prototype of the newly created object.
    • {} Also a method to create a new object, which is shorter and faster to use.
  • In Javascript, to write powerful programs, sometimes we need to check if an object matches the type we need, so we can use Object#hasOwnProperty to detect an object has a property. property is defined on its own, that is, not inherited from its prototype.
  • hasOwnProperty in Javascript is a method in Object, which checks whether a property exists in Object or not. If the specified property exists in the specified object, it will be returned true . If it does not exist, the value `fale.
  • Example: Write a function duckCount that returns the number of arguments passed to it that has the property ‘quack’ defined directly on them. Does not match values ​​inherited from the prototype.

Partial Application without Bind

  • Partial application allows you to create new functions from existing functions, while also modifying some arguments. After setting up the partially applied arguments, you’ll have a new function ready to multiply the rest of the arguments and be able to execute the original function.
  • More formally: Partial application refers to the process of modifying an argument to a function and creating another function of less rarity
  • apply() is the method that calls the specified function with a certain this value and arguments provided as an array (or an array-like object ).
  • Example: We have an add function that takes 2 arguments and adds them together

  • Now we use partiallyApply which takes a function and an argument to ‘Partial application’.
    • ‘partial application’ the first parameter of the add function is x

    • When we pass the argument to y , we can execute the original function add

Partial Application with Bind

  • The bind() method is a native Javascript function that helps us to achieve both partial and browser applications. It ensures the function is called from a this instance context, with the given n arguments.
  • Example: Use Function#bind to implement a logging function that allows you to specify the namespace. You have to take a string namespace and return a function that prints the message to the console with the namespace prepended. Make sure all arguments passed to the returned write function are printed.

Implement Map with Reduce

  • A map function applies a function to each item in an array and collects the results in a new Array.

  • Example: Use Array#Reduce to implement a simplified version of Array#map

Function Spies

  • Spies allow you to monitor a function, they show options for monitoring the number of calls, arguments, and return values. This allows you to write tests to verify the behavior of the function.
  • Example: Overriding an object’s specified method with new functionality while maintaining all the old behaviour.

Blocking Event Loop

  • Example: Modify the recursive repeat function provided in the boilerplate, so that it does not block the event loop (i.e. the timer and IO handler can fire). This necessarily requires asynchronous iteration.
  • The timeout is queued to fire after 100 milliseconds, will print the test’s results and exit the process. repeat should release control of the event loop to allow a timeout to interrupt before all operations complete.
  • Try to do as many operations as you can before the timeout runs out!

Trampoline

  • Is a small piece of code that quickly builds on the stack when the address of a nested function is taken.
  • Example: Fix the console below that uses a trampoline to repeatedly call itself synchronously. You can assume that the operation passed to iterate takes no arguments (or they are already bound to the function) and the return value doesn’t matter.

Async Loops

  • Example: Edit the code, the callback must be called with all loaded users. The order of users must match the order of the users id provided.

    • Fix

Recursion

  • Example: Implement a recursive function that returns a module’s unique dependencies and child dependencies in alphabetical order. Dependencies are printed as overlay versions.
  • Multiple versions of the same module are allowed, but duplicate modules of the same version must be removed.

Currying

  • Currying is an advanced technique for working with functions that simplifies a function by converting a function of many arguments into a sequence of functions of a single argument. It is not only used in Javascript but also used in other languages.
  • Example: Create a function ‘curryN’ that takes an arbitrary number of arguments, curryN will take two parameters
    • fn: The function we want to implement
    • n: Number of optional arguments for curry. If not provided, ‘curryN’ should use fn’s arity as the value for ‘n’.

Function Call

  • Example: Write a function that allows you to use Array.ptototype.slice without using slice.call or slice.apply to call it.
Share the news now

Source : Viblo