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)