Typescript Basics Flashcards
Loop through an object’s keys and values
for (const [key, value] of Object.entries(animals)) {
console.log(${key}: ${value}
);
}
Check if a key is in an object
if (key in myObject) { … }
*Loop through values in an array
for (const num of nums) { … }
Sort an array in ascending order
array.sort((a, b) => a - b)
Define a tree structure (eg BST)
class TreeNode {
value: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(value: number) {
this.value = value;
this.left = null;
this.right = null;
}
}
const node = new TreeNode(10)
Write a switch statement
const expr = ‘Papayas’;
switch (expr) {
case ‘Oranges’:
console.log(‘Oranges are $0.59 a pound.’);
break;
case ‘Mangoes’:
case ‘Papayas’:
console.log(‘Mangoes and papayas are $2.79 a pound.’);
break;
default:
console.log(Sorry, we are out of ${expr}.
);
}
Round decimal value down to nearest integer
Math.floor(n)
Round decimal value up to nearest integer
Math.ceil(n)
Round decimal value towards zero
Math.trunc(n)
Remove first element from array
const value = array.shift()
Get the max value in an array
Math.max(…array)
Create an empty array of n items
new Array(n).fill(null)
new Array(n).fill()
*Loop through indexes and values of array
for (const [index, value] of myArray.entries()) { … }
Remove key from object
delete myObj[key]
Get array of keys from object
Object.keys(myObj)
Convert number to string
n.toString()
OR
String(n)
Convert string to number
Number(x)
Create a class called Range that takes from
and to
as number arguments and includes a method called toString
that prints both. Then instantiate an instance of the class and call toString
class Range {
constructor(from, to) {
this.from = from;
this.to = to;
}
toString() {
return ${this.from}...${this.to}
;
}
}
const range = new Range(1, 4);
range.toString();
Create an async sleep function that resolves after n milisecondes
const sleep = async (n: number): Promise<void> => {
return new Promise(resolve => setTimeout(resolve, n));
}</void>
Create a timeout and cancel a timeout
const timeout = setTimeout(() => {…}, 10);
clearTimeout(timeout);
Given an array, return the 1st to 3rd (inclusive) elements as an array
array.slice(0, 3)
*Implement and use a Map (and iterate through keys and values of map)
const myMap = new Map();
myMap.set(‘a’, 1)
myMap.get(‘a’)
myMap.has(‘a’)
myMap.size // 1
myMap.delete(‘a’)
for (const [key, value] of myMap) {…}
*Implement and use a Set (and iterate through values of set)
const mySet = new Set(); // use new Set(array) to convert array to set
mySet.add(‘a’);
mySet.has(‘a’); // true
mySet.size; // 1
mySet.delete(‘a’);
for (const item of mySet) {…}
const myArray = […mySet]
Use reduce method to sum numbers in an array
[1, 2, 3].reduce((acc, curr) => acc + curr, 0)
Set the largest (smallest) number possible to the variable max (min)
const max = Infinity;
const min = -Infinity;
Determine if all elements in an array are below 4
[1, 2, 3].every((value) => value < 4)
Given an array, remove all elements that are less than 0
[-1, 2, 3].filter((value) => value >= 0);
Find the first index in an array for a specific value
[1, 2, 3].findIndex((el) => el === 2);
OR arr.indexOf(2)
Find the last index in an array of a specific value
[1, 2, 2, 3].findLastIndex((el) => el === 2);
OR arr.lastIndexOf(2)
Given the array [1, 2, [3, [4]]], generate the array [1, 2, 3, 4]
[1, 2, [3, [4]]].flat(Infinity)
*Determine if an array contains a value
[1, 2, 3, 4].includes(3);
*Determine if a variable is an array type
Array.isArray(myVar);
How do you run a function every n milliseconds?
const timerId = setInterval(() => myFunction, n);
clearInterval(timerId);
Create a new date
const date = new Date(year, month, day)
// note, month is zero-indexed
How do you check if a variable is an object type?
typeof x === ‘object’ && x !== null && !Array.isArray(x)
Add an element to the end of an array
array.push(value);