Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active December 4, 2024 10:34
Show Gist options
  • Save luisjunco/d7859451cc879fe45c226b6c65517126 to your computer and use it in GitHub Desktop.
Save luisjunco/d7859451cc879fe45c226b6c65517126 to your computer and use it in GitHub Desktop.

Practice: TypeScript functions

Intro

  • For this exercise, you can work on your local environment (if you have the TypeScript compiler installed).

  • Or, if you prefer, you can work on an online editor like Stackblitz. For example, you can write your TypeScript code here:

https://stackblitz.com/edit/typescript-vkcluy?file=index.ts


Iteration 1 - Create a function greetUser()

Requirements:

  • Name of the function: greetUser
  • Parameters:
    • userName (a string) - required.
    • languageCode (a string) - optional.
  • Return value:
    • If language is de, your function should return "Guten Morgen, [userName]!".
    • If language is es, your function should return "Buenos días, [userName]!".
    • If language is en (or no language is provided), your function should return "Good morning, [userName]!".

Iteration 2 - Create a function calcCircleArea()

Requirements:

  • Name of the function: calcCircleArea
  • Parameters:
    • radius (a number) - required.
  • Return value:
    • Return the area of the circle, calculated using the formula: PI * radius * radius
  • Notes:
    • You may need to do some research to get the value of PI in JS.
    • The returned value should be rounded to two decimal places.
    • If a radius of less than or equal to 0 is provided, return null indicating an invalid radius.

Bonus - Create a function binaryToDecimal()

Requirements:

  • Name of the function: binaryToDecimal
  • Parameters:
    • binaryString (a string) - required. The string should represent a binary number (e.g., '1010', '1101', '111111101').
  • Return value:
    • The function should return the decimal equivalent of the binary number.
    • If the provided string is not a valid binary number (contains characters other than '0' and '1'), return null indicating an invalid input.

Other bonus ideas:

  • practice TypeScript syntax with traditional functions and/or arrow functions
  • implement a function calculateRectangleArea()
  • implement a function calculateTriangleArea()

Solution: https://stackblitz.com/edit/typescript-kmbka6?file=index.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment