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)
*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)