One place for hosting & domains

      Functions

      How To Use Functions in TypeScript


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Creating and using functions is a fundamental aspect of any programming language, and TypeScript is no different. TypeScript fully supports the existing JavaScript syntax for functions, while also adding type information and function overloading as new features. Besides providing extra documentation to the function, type information also reduces the chances of bugs in the code because there’s a lower risk of passing invalid data types to a type-safe function.

      In this tutorial, you will start by creating the most basic functions with type information, then move on to more complex scenarios, like using rest parameters and function overloading. You will try out different code samples, which you can follow in your own TypeScript environment or the TypeScript Playground, an online environment that allows you to write TypeScript directly in the browser.

      Prerequisites

      To follow this tutorial, you will need:

      • An environment in which you can execute TypeScript programs to follow along with the examples. To set this up on your local machine, you will need the following:
      • If you do not wish to create a TypeScript environment on your local machine, you can use the official TypeScript Playground to follow along.
      • You will need sufficient knowledge of JavaScript, especially ES6+ syntax, such as destructuring, rest operators, and imports/exports. If you need more information on these topics, reading our How To Code in JavaScript series is recommended.
      • This tutorial will reference aspects of text editors that support TypeScript and show in-line errors. This is not necessary to use TypeScript, but does take more advantage of TypeScript features. To gain the benefit of these, you can use a text editor like Visual Studio Code, which has full support for TypeScript out of the box. You can also try out these benefits in the TypeScript Playground.

      All examples shown in this tutorial were created using TypeScript version 4.2.2.

      Creating Typed Functions

      In this section, you will create functions in TypeScript, and then add type information to them.

      In JavaScript, functions can be declared in a number of ways. One of the most popular is to use the function keyword, as is shown in the following:

      function sum(a, b) {
        return a + b;
      }
      

      In this example, sum is the name of the function, (a, b) are the arguments, and {return a + b;} is the function body.

      The syntax for creating functions in TypeScript is the same, except for one major addition: You can let the compiler know what types each argument or parameter should have. The following code block shows the general syntax for this, with the type declarations highlighted:

      function functionName(param1: Param1Type, param2: Param2Type): ReturnType {
        // ... body of the function
      }
      

      Using this syntax, you can then add types to the parameters of the sum function shown earlier:

      function sum(a: number, b: number) {
        return a + b;
      }
      

      This ensures that a and b are number values.

      You can also add the type of the returned value:

      function sum(a: number, b: number): number {
        return a + b;
      }
      

      Now TypeScript will expect the sum function to return a number value. If you call your function with some parameters and store the result value in a variable called result:

      const result = sum(1, 2);
      

      The result variable is going to have the type number. If you are using the TypeScript playground or are using a text editor that fully supports TypeScript, hovering over result with your cursor will show const result: number, showing that TypeScript has implied its type from the function declaration.

      If you called your function with a value that has a type other than the one expected by your function, the TypeScript Compiler (tsc) would give you the error 2345. Take the following call to the sum function:

      sum('shark', 'whale');
      

      This would give the following:

      Output

      Argument of type 'string' is not assignable to parameter of type 'number'. (2345)

      You can use any type in your functions, not just basic types. For example, imagine you have a User type that looks like this:

      type User = {
        firstName: string;
        lastName: string;
      };
      

      You could create a function that returns the full name of the user like the following:

      function getUserFullName(user: User): string {
        return `${user.firstName} ${user.lastName}`;
      }
      

      Most of the times TypeScript is smart enough to infer the return type of functions, so you can drop the return type from the function declaration in this case:

      function getUserFullName(user: User) {
        return `${user.firstName} ${user.lastName}`;
      }
      

      Notice you removed the : string part, which was the return type of your function. As you are returning a string in the body of your function, TypeScript correctly assumes your function has a string return type.

      To call your function now, you must pass an object that has the same shape as the User type:

      type User = {
        firstName: string;
        lastName: string;
      };
      
      function getUserFullName(user: User) {
        return `${user.firstName} ${user.lastName}`;
      }
      
      const user: User = {
        firstName: "Jon",
        lastName: "Doe"
      };
      
      const userFullName = getUserFullName(user);
      

      This code will successfully pass the TypeScript type-checker. If you hover over the userFullName constant in your editor, the editor will identify its type as string.

      Optional Function Parameters in TypeScript

      Having all parameters is not always required when creating functions. In this section, you will learn how to mark function parameters as optional in TypeScript.

      To turn a function parameter into an optional one, add the ? modifier right after the parameter name. Given a function parameter param1 with type T, you could make param1 an optional parameter by adding ?, as highlighted in the following:

      param1?: T
      

      For example, add an optional prefix parameter to your getUserFullName function, which is an optional string that can be added as a prefix to the user’s full name:

      type User = {
        firstName: string;
        lastName: string;
      };
      
      function getUserFullName(user: User, prefix?: string) {
        return `${prefix ?? ''}${user.firstName} ${user.lastName}`;
      }
      

      In the first highlighted part of this code block, you are adding an optional prefix parameter to your function, and in the second highlighted part you are prefixing the user’s full name with it. To do that, you are using the nullish coalescing operator ??. This way, you are only going to use the prefix value if it is defined; otherwise, the function will use an empty string.

      Now you can call your function with or without the prefix parameter, as shown in the following:

      type User = {
        firstName: string;
        lastName: string;
      };
      
      function getUserFullName(user: User, prefix?: string) {
        return `${prefix ?? ''} ${user.firstName} ${user.lastName}`;
      }
      
      const user: User = {
        firstName: "Jon",
        lastName: "Doe"
      };
      
      const userFullName = getUserFullName(user);
      const mrUserFullName = getUserFullName(user, 'Mr. ');
      

      In this case, the value of userFullName will be Jon Doe, and the value of mrUserFullName will be Mr. Jon Doe.

      Note that you cannot add an optional parameter before a required one; it must be listed last in the series, as is done with (user: User, prefix?: string). Listing it first would make the TypeScript Compiler return the error 1016:

      Output

      A required parameter cannot follow an optional parameter. (1016)

      Typed Arrow Function Expressions

      So far, this tutorial has shown how to type normal functions in TypeScript, defined with the function keyword. But in JavaScript, you can define a function in more than one way, such as with arrow functions. In this section, you will add types to arrow functions in TypeScript.

      The syntax for adding types to arrow functions is almost the same as adding types to normal functions. To illustrate this, change your getUserFullName function into an arrow function expression:

      const getUserFullName = (user: User, prefix?: string) => `${prefix ?? ''}${user.firstName} ${user.lastName}`;
      

      If you wanted to be explicit about the return type of your function, you would add it after the (), as shown in the highlighted code in the following block:

      const getUserFullName = (user: User, prefix?: string): string => `${prefix ?? ''}${user.firstName} ${user.lastName}`;
      

      Now you can use your function exactly like before:

      type User = {
        firstName: string;
        lastName: string;
      };
      
      const getUserFullName = (user: User, prefix?: string) => `${prefix ?? ''}${user.firstName} ${user.lastName}`;
      
      const user: User = {
        firstName: "Jon",
        lastName: "Doe"
      };
      
      const userFullName = getUserFullName(user);
      

      This will pass the TypeScript type-checker with no error.

      Note: Remember that everything valid for functions in JavaScript is also valid for functions in TypeScript. For a refresher on these rules, check out our How To Define Functions in JavaScript tutorial.

      Function Types

      In the previous sections, you added types to the parameters and return values for functions in TypeScript. In this section, you are going to learn how to create function types, which are types that represent a specific function signature. Creating a type that matches a specific function is especially useful when passing functions to other functions, like having a parameter that is itself a function. This is a common pattern when creating functions that accept callbacks.

      The syntax for creating your function type is similar to creating an arrow function, with two differences:

      • You remove the function body.
      • You make the function declaration return the return type itself.

      Here is how you would create a type that matches the getUserFullName function you have been using:

      type User = {
        firstName: string;
        lastName: string;
      };
      
      type PrintUserNameFunction = (user: User, prefix?: string) => string;
      

      In this example, you used the type keyword to declare a new type, then provided the type for the two parameters in the parentheses and the type for the return value after the arrow.

      For a more concrete example, imagine you are creating an event listener function called onEvent, which receives as the first parameter the event name, and as the second parameter the event callback. The event callback itself would receive as the first parameter an object with the following type:

      type EventContext = {
        value: string;
      };
      

      You can then write your onEvent function like this:

      type EventContext = {
        value: string;
      };
      
      function onEvent(eventName: string, eventCallback: (target: EventContext) => void) {
        // ... implementation
      }
      

      Notice that the type of the eventCallback parameter is a function type:

      eventCallback: (target: EventTarget) => void
      

      This means that your onEvent function expects another function to be passed in the eventCallback parameter. This function should accept a single argument of the type EventTarget. The return type of this function is ignored by your onEvent function, and so you are using void as the type.

      Using Typed Asynchronous Functions

      When working with JavaScript, it is relatively common to have asynchronous functions. TypeScript has a specific way to deal with this. In this section, you are going to create asynchronous functions in TypeScript.

      The syntax for creating asynchronous functions is the same as the one used for JavaScript, with the addition of allowing types:

      async function asyncFunction(param1: number) {
        // ... function implementation ...
      }
      

      There is one major difference between adding types to a normal function and adding types to an asynchronous function: In an asynchronous function, the return type must always be the Promise<T> generic. The Promise<T> generic represents the Promise object that is returned by an asynchronous function, where T is the type of the value the promise resolves to.

      Imagine you have a User type:

      type User = {
        id: number;
        firstName: string;
      };
      

      Imagine also that you have a few user objects in a data store. This data could be stored anywhere, like in a file, a database, or behind an API request. For simplicity, in this example you will be using an array:

      type User = {
        id: number;
        firstName: string;
      };
      
      const users: User[] = [
        { id: 1, firstName: "Jane" },
        { id: 2, firstName: "Jon" }
      ];
      

      If you wanted to create a type-safe function that retrieves a user by ID in an asynchronous way, you could do it like this:

      async function getUserById(userId: number): Promise<User | null> {
        const foundUser = users.find(user => user.id === userId);
      
        if (!foundUser) {
          return null;
        }
      
        return foundUser;
      }
      

      In this function, you are first declaring your function as asynchronous:

      async function getUserById(userId: number): Promise<User | null> {
      

      Then you are specifying that it accepts as the first parameter the user ID, which must be a number:

      async function getUserById(userId: number): Promise<User | null> {
      

      The return type of getUserById is a Promise that resolves to either User or null. You are using the union type User | null as the type parameter to the Promise generic.

      User | null is the T in Promise<T>:

      async function getUserById(userId: number): Promise<User | null> {
      

      Call your function using await and store the result in a variable called user:

      type User = {
        id: number;
        firstName: string;
      };
      
      const users: User[] = [
        { id: 1, firstName: "Jane" },
        { id: 2, firstName: "Jon" }
      ];
      
      async function getUserById(userId: number): Promise<User | null> {
        const foundUser = users.find(user => user.id === userId);
      
        if (!foundUser) {
          return null;
        }
      
        return foundUser;
      }
      
      async function runProgram() {
        const user = await getUserById(1);
      }
      

      Note: You are using a wrapper function called runProgram because you cannot use await in the top level of a file. Doing so would cause the TypeScript Compiler to emit the error 1375:

      Output

      'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module. (1375)

      If you hover over user in your editor or in the TypeScript Playground, you’ll find that user has the type User | null, which is exactly the type the promise returned by your getUserById function resolves to.

      If you remove the await and just call the function directly, the Promise object is returned:

      async function runProgram() {
        const userPromise = getUserById(1);
      }
      

      If you hover over userPromise, you’ll find that it has the type Promise<User | null>.

      Most of the time, TypeScript can infer the return type of your async function, just like it does with non-async functions. You can therefore omit the return type of the getUserById function, as it is still correctly inferred to have the type Promise<User | null>:

      async function getUserById(userId: number) {
        const foundUser = users.find(user => user.id === userId);
      
        if (!foundUser) {
          return null;
        }
      
        return foundUser;
      }
      

      Adding Types to Rest Parameters

      Rest parameters are a feature in JavaScript that allows a function to receive many parameters as a single array. In this section, you will use rest parameters with TypeScript.

      Using rest parameters in a type-safe way is completely possible by using the rest parameter followed by the type of the resulting array. Take for example the following code, where you have a function called sum that accepts a variable amount of numbers and returns their total sum:

      function sum(...args: number[]) {
        return args.reduce((accumulator, currentValue) => {
          return accumulator + currentValue;
        }, 0);
      }
      

      This function uses the .reduce Array method to iterate over the array and add the elements together. Notice the rest parameter args highlighted here. The type is being set to an array of numbers: number[].

      Calling your function works normally:

      function sum(...args: number[]) {
        return args.reduce((accumulator, currentValue) => {
          return accumulator + currentValue;
        }, 0);
      }
      
      const sumResult = sum(2, 4, 6, 8);
      

      If you call your function using anything other than a number, like:

      const sumResult = sum(2, "b", 6, 8);
      

      The TypeScript Compiler will emit the error 2345:

      Output

      Argument of type 'string' is not assignable to parameter of type 'number'. (2345)

      Using Function Overloads

      Programmers sometime need a function to accept different parameters depending on how the function is called. In JavaScript, this is normally done by having a parameter that may assume different types of values, like a string or a number. Setting multiple implementations to the same function name is called function overloading.

      With TypeScript, you can create function overloads that explicitly describe the different cases that they address, improving the developer experience by document each implementation of the overloaded function separately. This section will go through how to use function overloading in TypeScript.

      Imagine you have a User type:

      type User = {
        id: number;
        email: string;
        fullName: string;
        age: number;
      };
      

      And you want to create a function that can look up a user using any of the following information:

      • id
      • email
      • age and fullName

      You could create such a function like this:

      function getUser(idOrEmailOrAge: number | string, fullName?: string): User | undefined {
        // ... code
      }
      

      This function uses the | operator to compose a union of types for idOrEmailOrAge and for the return value.

      Next, add function overloads for each way you want your function to be used, as shown in the following highlighted code:

      type User = {
        id: number;
        email: string;
        fullName: string;
        age: number;
      };
      
      function getUser(id: number): User | undefined;
      function getUser(email: string): User | undefined;
      function getUser(age: number, fullName: string): User | undefined;
      
      function getUser(idOrEmailOrAge: number | string, fullName?: string): User | undefined {
        // ... code
      }
      

      This function has three overloads, one for each way to retrieve a user. When creating function overloads, you add the function overloads before the function implementation itself. The function overloads do not have a body; they just have the list of parameters and the return type.

      Next, you implement the function itself, which should have a parameter list that is compatible with all function overloads. In the previous example, your first parameter can be either a number or a string, since it can be the id, the email, or the age:

      function getUser(id: number): User | undefined;
      function getUser(email: string): User | undefined;
      function getUser(age: number, fullName: string): User | undefined;
      
      function getUser(idOrEmailOrAge: number | string, fullName?: string): User | undefined {
        // ... code
      }
      

      You therefore set the type of the idOrEmailorAge parameter in your function implementation to be number | string. This way, it is compatible with all the overloads of your getUser function.

      You are also adding an optional parameter to your function, for when the user is passing a fullName:

      function getUser(id: number): User | undefined;
      function getUser(email: string): User | undefined;
      function getUser(age: number, fullName: string): User | undefined;
      
      function getUser(idOrEmailOrAge: number | string, fullName?: string): User | undefined {
        // ... code
      }
      

      Implementing your function could be like the following, where you are using a users array as the data store of your users:

      type User = {
        id: number;
        email: string;
        fullName: string;
        age: number;
      };
      
      const users: User[] = [
        { id: 1, email: "jane_doe@example.com", fullName: "Jane Doe" , age: 35 },
        { id: 2, email: "jon_do@example.com", fullName: "Jon Doe", age: 35 }
      ];
      
      function getUser(id: number): User | undefined;
      function getUser(email: string): User | undefined;
      function getUser(age: number, fullName: string): User | undefined;
      
      function getUser(idOrEmailOrAge: number | string, fullName?: string): User | undefined {
        if (typeof idOrEmailOrAge === "string") {
          return users.find(user => user.email === idOrEmailOrAge);
        }
      
        if (typeof fullName === "string") {
          return users.find(user => user.age === idOrEmailOrAge && user.fullName === fullName);
        } else {
          return users.find(user => user.id === idOrEmailOrAge);
        }
      }
      
      const userById = getUser(1);
      const userByEmail = getUser("jane_doe@example.com");
      const userByAgeAndFullName = getUser(35, "Jon Doe");
      

      In this code, if idOrEmailOrAge is a string, then you can search for the user with the email key. The following conditional assumes idOrEmailOrAge is a number, so it is either the id or the age, depending on if fullName is defined.

      One interesting aspect of function overloads is that in most editors, including VS Code and the TypeScript Playground, as soon as you type the function name and open the first parenthesis to call the function, a pop-up will appear with all the overloads available, as shown in the following image:

      Overloads Popup

      If you add a comment to each function overload, the comment will also be in the pop-up as a source of documentation. For example, add the following highlighted comments to the example overloads:

      ...
      /**
       * Get a user by their ID.
       */
      function getUser(id: number): User | undefined;
      /**
       * Get a user by their email.
       */
      function getUser(email: string): User | undefined;
      /**
       * Get a user by their age and full name.
       */
      function getUser(age: number, fullName: string): User | undefined;
      ...
      

      Now when you hover over these functions, the comment will show up for each overload, as shown in the following animation:

      Overloads Popup with Comments

      User-Defined Type Guards

      The last feature of functions in TypeScript that this tutorial will examine is user-defined type guards, which are special functions that allow TypeScript to better infer the type of some value. These guards enforce certain types in conditional code blocks, where the type of a value may be different depending on the situation. These are especially useful when using the Array.prototype.filter function to return a filtered array of data.

      One common task when adding values conditionally to an array is to check for some conditions and then only add the value if the condition is true. If the value is not true, the code adds a false Boolean to the array. Before using that array, you can filter it using .filter(Boolean) to make sure only truthy values are returned.

      When called with a value, the Boolean constructor returns true or false, depending on if this value is a Truthy or Falsy value.

      For example, imagine you have an array of strings, and you only want to include the string production to that array if some other flag is true:

      const isProduction = false
      
      const valuesArray = ['some-string', isProduction && 'production']
      
      function processArray(array: string[]) {
        // do something with array
      }
      
      processArray(valuesArray.filter(Boolean))
      

      While this is, at runtime, perfectly valid code, the TypeScript Compiler will give you the error 2345 during compilation:

      Output

      Argument of type '(string | boolean)[]' is not assignable to parameter of type 'string[]'. Type 'string | boolean' is not assignable to type 'string'. Type 'boolean' is not assignable to type 'string'. (2345)

      This error is saying that, at compile-time, the value passed to processArray is interpreted as an array of false | string values, which is not what the processArray expected. It expects an array of strings: string[].

      This is one case where TypeScript is not smart enough to infer that by using .filter(Boolean) you are removing all falsy values from your array. However, there is one way to give this hint to TypeScript: using user-defined type guards.

      Create a user-defined type guard function called isString:

      function isString(value: any): value is string {
        return typeof value === "string"
      }
      

      Notice the return type of the isString function. The way to create user-defined type guards is by using the following syntax as the return type of a function:

      parameterName is Type
      

      Where parameterName is the name of the parameter you are testing, and Type is the expected type the value of this parameter has if this function returns true.

      In this case, you are saying that value is a string if isString returns true. You are also setting the type of your value parameter to any, so it works with any type of value.

      Now, change your .filter call to use your new function instead of passing it the Boolean constructor:

      const isProduction = false
      
      const valuesArray = ['some-string', isProduction && 'production']
      
      function processArray(array: string[]) {
        // do something with array
      }
      
      function isString(value: any): value is string {
        return typeof value === "string"
      }
      
      processArray(valuesArray.filter(isString))
      

      Now the TypeScript compiler correctly infers that the array passed to processArray only contains strings, and your code compiles correctly.

      Conclusion

      Functions are the building block of applications in TypeScript, and in this tutorial you learned how to build type-safe functions in TypeScript and how to take advantage of function overloads to better document all variants of a single function. Having this knowledge will allow for more type-safe and easy-to-maintain functions throughout your code.

      For more tutorials on TypeScript, check out our TypeScript Topic page.



      Source link

      How To Use the all, any, max, and min Functions in Python


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Python includes a number of built-in functions—these are global Python functions that can be called from any Python code without importing additional modules. For example, you can always call the print built-in function to output text.

      Several of the built-in functions (all, any, max, and min among them) take iterables of values as their argument and return a single value. An iterable is a Python object that can be “iterated over”, that is, it will return items in a sequence such that you can use it in a for loop. Built-in functions are useful when, for example, you want to determine if all or any of the elements in a list meet a certain criteria, or find the largest or smallest element in a list.

      In this tutorial, you will use the built-in functions all, any, max, and min.

      Prerequisites

      To get the most out of this tutorial, it is recommended to have:

      Using all

      The built-in function all checks if every element in an iterable is True. For example:

      all([True, True])
      

      If you run the previous code, you will receive this output:

      Output

      True

      In this first example, you call all and give it a list with two elements (two True Boolean values). Since every element in the iterable is True, the output was True.

      all will return False if one or more elements in the given iterable is False:

      all([True, False, True])
      

      If you run the previous code, you’ll receive this output:

      Output

      False

      You call all with a list containing three elements including one False Boolean value. Since one of the elements in the iterable was False, the output of the call to all was False.

      Notably, all stops iterating and immediately returns False as soon as it encounters the first False entry in an iterable. So, all can be useful if you want to check successive conditions that may build on each other, but return immediately as soon as one condition is False.

      A special case to be aware of is when all is given an empty iterable:

      all([])
      

      If you run the previous code, you’ll receive this output:

      Output

      True

      When you give all an empty iterable (for example, an empty list like all([])), its return value is True. So, all returns True if every element in the iterable is True or there are 0 elements.

      all is particularly helpful when combined with generators and custom conditions. Using all is often shorter and more concise than if you were to write a full-fledged for loop. Let’s consider an example to find out whether there are elements in a list that start with "s":

      animals = ["shark", "seal", "sea urchin"]
      all(a.startswith("s") for a in animals)
      

      If you run the previous code, you will receive this output:

      Output

      True

      You call all with a generator as its argument. The generator produces a Boolean for each element in the animals list based on whether or not the animal starts with the letter s. The final return value is True because every element in the animals list starts with s.

      Note: You can often use Generator expressions in place of list comprehensions as a way of saving memory. For example, consider all(i < 8 for i in range(3)) and all([i < 8 for i in range(3)]). Both statements return True because 0, 1, 2 are all less than 8. The second example (which uses a list comprehension), however, has the added overhead of implicitly creating a list three entries long ([True, True, True]) and then passing that list to the all function. The first example (which uses generator expressions), by contrast, passes a generator object to the all function, which the all function iterates over directly without the overhead of an intermediary list.

      Consider that the equivalent code written using a full-fledged for loop would have been significantly more verbose:

      animals = ["shark", "seal", "sea urchin"]
      
      def all_animals_start_with_s(animals):
          for a in animals:
              if not a.startswith("s"):
                  return False
          return True
      
      print(all_animals_start_with_s(animals))
      

      Without all, your code for determining if all the animals start with the letter s requires several more lines to implement.

      Next, you’ll look at the sibling function to all: any.

      Using any

      You can use the built-in function any to check if any element in an iterable is True. For example:

      any([False, True])
      

      If you run the previous code, you’ll receive this output:

      Output

      True

      You call any and give it a list with two elements (a False Boolean value and a True Boolean value). Since one or more element in the iterable was True, the output was also True.

      any will return False if, and only if, 0 of the elements in the given iterable are True:

      all([False, False, False])
      

      If you run the previous code, you’ll receive this output:

      Output

      False

      You call any with a list containing three elements (all False Boolean values). Since 0 of the elements in the iterable is True, the output of the call to any is False.

      Notably, any stops iterating and immediately returns True as soon as it encounters the first True entry in an iterable. So, any can be useful if you want to check successive conditions, but return immediately as soon as one condition is True.

      any—like its sibling method all—is particularly helpful when combined with generators and custom conditions (in place of a full for loop). Let’s consider an example to find out whether there are elements in a list that end with "urchin":

      animals = ["shark", "seal", "sea urchin"]
      any(s.endswith("urchin") for s in animals)
      

      You will receive this output:

      Output

      True

      You call any with a generator as its argument. The generator produces a Boolean for each element in the animals list based on whether or not the animal ends with urchin. The final return value is True because one element in the animals list ends with urchin.

      Note: When any is given an empty iterable (for example, an empty list like any([])), its return value is False. So, any returns False if there are 0 elements in the iterable or all the elements in the iterable are also False.

      Next, you’ll review another built-in function: max.

      Using max

      The built-in function max returns the largest element given in its arguments. For example:

      max([0, 8, 3, 1])
      

      max is given a list with four integers as its argument. The return value of max is the largest element in that list: 8.

      The output will be the following:

      Output

      8

      If given two or more positional arguments (as opposed to a single positional argument with an iterable), max returns the largest of the given arguments:

      max(1, -1, 3)
      

      If you run the previous code, you will receive this output:

      Output

      3

      max is given three individual arguments, the largest of which being 3. So, the return value of the call to max is 3.

      Just like any and all, max is particularly helpful because it requires fewer lines to use than equivalent code written as a full for loop.

      max can also deal with objects more complex than numbers. For example, you can use max with dictionaries or other custom objects in your program. max can accommodate these objects by using its keyword argument named key.

      You can use the key keyword argument to define a custom function that determines the value used in the comparisons to determine the maximum value. For example:

      entries = [{"id": 9}, {"id": 17}, {"id": 4}]
      max(entries, key=lambda x: x["id"])
      

      The output will be the following:

      Output

      {'id': 17}

      You call max with a list of dictionaries as its input. You give an anonymous lambda function as the key keyword argument. max calls the lambda function for every element in the entries list and returns the value of the "id" key of the given element. The final return value is the second element in entries: {"id": 17}. The second element in entries had the largest "id" value, and so was deemed to be the maximum element.

      Note that when max is called with an empty iterable, it refuses to operate and instead raises a ValueError:

      max([])
      

      If you run this code, you will receive the following output:

      Output

      Traceback (most recent call last): File "max.py", line 1, in <module> max([]) ValueError: max() arg is an empty sequence

      You call max with an empty list as its argument. max does not accept this as a valid input, and raises a ValueError Exception instead.

      max has a counterpart called min, which you’ll review next.

      Using min

      The built-in function min returns the smallest element given in its arguments. For example:

      min([8, 0, 3, 1])
      

      You give min a list with four integers as its argument. The return value of min is the smallest element in that list: 0.

      The output will be:

      Output

      0

      If given two or more positional arguments (as opposed to a single positional argument with an iterable), min returns the smallest of the given arguments:

      min(1, -1, 3)
      

      If you run the previous code, you will receive this output:

      Output

      -1

      You give min three individual arguments, the smallest of which being -1. So, the return value of the call to min is -1.

      Like max, min supports the keyword argument named key so that you can pass objects more complex than numbers into it. Using the key argument allows you to use the min function with any custom objects your program might define.

      You can use the key keyword argument to define a custom function that determines the value used in the comparisons to determine the minimum value. For example:

      entries = [{"id": 9}, {"id": 17}, {"id": 4}]
      min(entries, key=lambda x: x["id"])
      

      Output

      {'id': 4}

      You call min with a list of dictionaries as its input. You give an anonymous lambda function as the key keyword argument. min calls the lambda function for every element in the entries list and returns the value of the "id" key of the given element. The final return value is the third element in entries: {"id": 4}. The third element in entries had the smalled "id" value, and so was deemed to be the minimum element.

      Like max, when you call min with an empty iterable, it refuses to operate and instead raises a ValueError:

      min([])
      

      If you run the previous code, you will receive this output:

      Output

      Traceback (most recent call last): File "min.py", line 1, in <module> min([]) ValueError: min() arg is an empty sequence

      You call min with an empty list as its argument. min does not accept this as a valid input, and raises a ValueError Exception instead.

      Conclusion

      In this tutorial, you used the Python built-in functions all, any, max, and min. You can learn more about the functions all, any, max, and min and other Python built-in in the Python docs.

      For more information on other Python built-ins, you can also check out Built-in Python 3 Functions for Working with Numbers, How To Use the Python Map Function, and How To Use the Python Filter Function.



      Source link

      Exploring Async/Await Functions in JavaScript


      Introduction

      Promises give us an easier way to deal with asynchrony in our code in a sequential manner. Considering that our brains are not designed to deal with asynchronicity efficiently, this is a much welcome addition. Async/await functions, a new addition with ES2017 (ES8), help us even more in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes.

      The functionality achieved using async functions can be recreated by combining promises with generators, but async functions give us what we need without any extra boilerplate code.

      Simple Example

      In the following example, we first declare a function that returns a promise that resolves to a value of 🤡 after 2 seconds. We then declare an async function and await for the promise to resolve before logging the message to the console:

      function scaryClown() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('🤡');
          }, 2000);
        });
      }
      
      async function msg() {
        const msg = await scaryClown();
        console.log('Message:', msg);
      }
      
      msg(); // Message: 🤡 <-- after 2 seconds
      

      await is a new operator used to wait for a promise to resolve or reject. It can only be used inside an async function.

      The power of async functions becomes more evident when there are multiple steps involved:

      function who() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('🤡');
          }, 200);
        });
      }
      
      function what() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('lurks');
          }, 300);
        });
      }
      
      function where() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('in the shadows');
          }, 500);
        });
      }
      
      async function msg() {
        const a = await who();
        const b = await what();
        const c = await where();
      
        console.log(`${ a } ${ b } ${ c }`);
      }
      
      msg(); // 🤡 lurks in the shadows <-- after 1 second
      

      A word of caution however, in the above example each step is done sequentially, with each additional step waiting for the step before to resolve or reject before continuing. If you instead want the steps to happen in parallel, you can simply use Promise.all to wait for all the promises to have fulfilled:

      // ...
      
      async function msg() {
        const [a, b, c] = await Promise.all([who(), what(), where()]);
      
        console.log(`${ a } ${ b } ${ c }`);
      }
      
      msg(); // 🤡 lurks in the shadows <-- after 500ms
      

      Promise.all returns an array with the resolved values once all the passed-in promises have resolved.

      In the above we also make use of some nice array destructuring to make our code succinct.

      Promise-Returning

      Async functions always return a promise, so the following may not produce the result you’re after:

      async function hello() {
        return 'Hello Alligator!';
      }
      
      const b = hello();
      
      console.log(b); // [object Promise] { ... }
      

      Since what’s returned is a promise, you could do something like this instead:

      async function hello() {
        return 'Hello Alligator!';
      }
      
      const b = hello();
      
      b.then(x => console.log(x)); // Hello Alligator!
      

      …or just this:

      async function hello() {
        return 'Hello Alligator!';
      }
      
      hello().then(x => console.log(x)); // Hello Alligator!
      

      Different Forms

      So far with our examples we saw the async function as a function declaration, but you we can also define async function expressions and async arrow functions:

      Async Function Expression

      Here’s the async function from our first example, but defined as a function expression:

      const msg = async function() {
        const msg = await scaryClown();
        console.log('Message:', msg);
      }
      

      Async Arrow Function

      Here’s that same example once again, but this time defined as an arrow function:

      const msg = async () => {
        const msg = await scaryClown();
        console.log('Message:', msg);
      }
      

      Error Handling

      Something else that’s very nice about async functions is that error handling is also done completely synchronously, using good old try…catch statements. Let’s demonstrate by using a promise that will reject half the time:

      function yayOrNay() {
        return new Promise((resolve, reject) => {
          const val = Math.round(Math.random() * 1); // 0 or 1, at random
      
          val ? resolve('Lucky!!') : reject('Nope 😠');
        });
      }
      
      async function msg() {
        try {
          const msg = await yayOrNay();
          console.log(msg);
        } catch(err) {
          console.log(err);
        }
      }
      
      msg(); // Lucky!!
      msg(); // Lucky!!
      msg(); // Lucky!!
      msg(); // Nope 😠
      msg(); // Lucky!!
      msg(); // Nope 😠
      msg(); // Nope 😠
      msg(); // Nope 😠
      msg(); // Nope 😠
      msg(); // Lucky!!
      

      Given that async functions always return a promise, you can also deal with unhandled errors as you would normally using a catch statement:

      async function msg() {
        const msg = await yayOrNay();
        console.log(msg);
      }
      
      msg().catch(x => console.log(x));
      

      This synchronous error handling doesn’t just work when a promise is rejected, but also when there’s an actual runtime or syntax error happening. In the following example, the second time with call our msg function we pass in a number value that doesn’t have a toUpperCase method in its prototype chain. Our try…catch block catches that error just as well:

      function caserUpper(val) {
        return new Promise((resolve, reject) => {
          resolve(val.toUpperCase());
        });
      }
      
      async function msg(x) {
        try {
          const msg = await caserUpper(x);
          console.log(msg);
        } catch(err) {
          console.log('Ohh no:', err.message);
        }
      }
      
      msg('Hello'); // HELLO
      msg(34); // Ohh no: val.toUpperCase is not a function
      

      Async Functions With Promise-Based APIS

      As we showed in our primer to the Fetch API, web APIs that are promise-based are a perfect candidate for async functions:

      async function fetchUsers(endpoint) {
        const res = await fetch(endpoint);
        let data = await res.json();
      
        data = data.map(user => user.username);
      
        console.log(data);
      }
      
      fetchUsers('https://jsonplaceholder.typicode.com/users');
      // ["Bret", "Antonette", "Samantha", "Karianne", "Kamren", "Leopoldo_Corkery", "Elwyn.Skiles", "Maxime_Nienow", "Delphine", "Moriah.Stanton"]
      

      <%>[note]
      Browser Support:
      As of 2020, 94% of browsers worldwide can handle async/await in javascript Notable exceptions are IE11 and Opera Mini.

      Conclusion

      Before Async/await functions, JavaScript code that relied on lots of asynchronous events (for example: code that made lots of calls to APIs) would end up in what some called “callback hell” – A chain of functions and callbacks that was very difficult to read and understand.

      Async and await allow us to write asynchronous JavaScript code that reads much more clearly.



      Source link