80/20 Rule
These 20% of the techniques are used 80% of the time when solving the DSL problems:
-
["e", "l", "p", "p", "a"].join("")
Concatenation of all elements of the array -
str.split("")
Turns string into an arraylet str = "Apple"; const arr = str.split("")
-
toLowerCase()
-
toString()
-
parseInt()
-
split()
-
join()
-
slice()
-
for of
Loop -> Use to iterate through a string or an array
let string = "Ambreen" for(let char of string){ console.log(char) }
-
Math.floor(nums.length / 2)
-
for In
Loop -> Use to iterate through an object -
Unicode Strings
z = 122
a= 97 -
The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
char.charCodeAt()
-
String.fromCharCode() method returns a string created from the specified sequence of UTF-16 code units.
String.fromCharCode(charCode)
-
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
indexOf(searchElement)
indexOf(searchElement, fromIndex)
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
- Sort a number array:
// https://www.w3schools.com/js/js_array_sort.asp
// By default, the sort() function sorts values as strings.
// You can fix this by providing a compare function
array.sort((a,b) => a-b);
- Build Character Map:
function buildCharMap(str) {
const charMap = {};
for (let char of str) {
charMap[char] = charMap[char] + 1 || 1;
}
return charMap;
}
- Compare the size of 2 character maps
if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
return false;
}
- Getting values for all keys from a hash map
Object.values(anagramMap)
- Regex
Regular Expression: word.replace(/[^\w]/g, "");
var patt1 = /\w/g
//A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.
const str = "RAIL! SAFETY_!";
function cleanString(str) {
return str
.replace(/[^\w]/g, '').replace('_', '')
.toLowerCase()
.split('')
.sort()
.join('');
}
console.log(cleanString(str)); //RAILSAFETY
Converting Set to array
function intersection(nums1, nums2) {
const set = new Set(nums1);
const filteredSet = new Set(nums2.filter((n) => set.has(n)));
return [ ...filteredSet ];
}
Filtering out the alphabet character only
// Filtering out the alphabet character only:
function filterAlphbetOnly(str){
const regex = /[a-zA-Z]/g;
let filteredArr = str.match(regex);
let reversedArr = reverseArr(filteredArr);
return reversedArr;
}
JS Filter Method
const age = [23, 45, 20, 20, 55, 65];
// console.log(age.filter(age40AndAbove));
console.log(age.filter((age)=> {
return age>=40
}));
// function age40AndAbove(age){
// return age>=40
// }
Common JS Array built-in functions
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array
const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2);
console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]
Common Mathematics functions
Math.abs()
The Math.abs() function returns the absolute value of a number. That is, it returns x if x is positive or zero, and the negation of x if x is negative.
Math.sign()
The Math.sign() function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed into Math.sign() is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will not be returned. (returns 1 if number is positive else returns -1)
Math.max()
The Math.max() function returns the largest of the zero or more numbers given as input parameters
The Math.floor()
function returns the largest integer less than or equal to a given number.
Sorting
Bubble Sort - Element Swapping - 2 nested loops - O(n^2)
Merge Sort - O(n log n)
- Divide the array recursively until the elements are two or less.
- We know how to sort two items, so we sort them iteratively (base case).
- The final step is merging: we merge in taking one by one from each array such that they are in ascending order.
Searching:
Binary search - Split the problem in half on each iteration O(log n).
Random Number Generation
Generate a random number between 0 and 10 (not including 10)
Math.floor(Math.random()*10)
function getRandomInt(x){
return Math.floor(Math.random() * x);
}
getRandomInt(10)
Date.now()
Number is Integer
The Number.isInteger() method determines whether the passed value is an integer
Using filter Function
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const filterList = (arr) => {
const filteredIntegers = arr.filter(num => Number.isInteger(num) && num > 0);
return filteredIntegers;
};
const filteredIntegers = filterList(realNumberArray);
console.log(filteredIntegers);
Using map & filter functions togather
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
const squaredIntegers = arr.filter(num => Number.isInteger(num) && num > 0).map(x => x * x);
return squaredIntegers;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
Setting default value
const increment = (function() {
return function increment(number, value = 1) {
return number + value;
};
})();
console.log(increment(5, 2));
console.log(increment(5));
Using Rest Operator for Function Parameter
const sum = (function() {
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3, 4));
Using the Spread Operator to make a copy of an array
- Spreads out an array (i.e. makes a copy) into its individual parts
//Original array is mutated
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
arr2 = arr1;
arr1[0] = 'potato'
})();
console.log(arr2); //outputs: ["potato", "FEB", "MAR", "APR", "MAY"] as both arr1 & arr2 are still pointing to the same array.
//Here arr2 will NOT be equal to arr1 instead it will be equal to the content of the arr1
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
arr2 = [...arr1];
arr1[0] = 'potato'
})();
console.log(arr2);
Destructuring
var voxel = {x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
const { x : a, y : b, z : c } = voxel; // a = 3.6, b = 7.4, c = 6.54
const AVG_TEMPERATURES = {
today: 77.5,
tomorrow: 79
};
function getTempOfTmrw(avgTemperatures) {
const { tomorrow : tempOfTomorrow } = avgTemperatures; // change this line
return tempOfTomorrow;
}
console.log(getTempOfTmrw(AVG_TEMPERATURES)); // should be 79
Destructuring from Nested Objects
const LOCAL_FORECAST = {
today: { min: 72, max: 83 },
tomorrow: { min: 73.3, max: 84.6 }
};
function getMaxOfTmrw(forecast) {
"use strict";
const { tomorrow : { max : maxOfTomorrow }} = forecast;
return maxOfTomorrow;
}
console.log(getMaxOfTmrw(LOCAL_FORECAST));
Use Destructuring Assignment to assign variables from Arrays
const [z, x, , y] = [1, 2, 3, 4, 5, 6];
console.log(z, x, y);
//Output: 1,2,4
//Uisng destructuring to switch values
let a = 8, b = 6;
(() => {
"use strict";
[a, b] = [b, a]
})();
console.log(a); //6
console.log(b); //8
Using Destructuring Assignment with the Rest operator to Reassign Array Element
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
const [ , , ...arr] = list;
return arr;
}
const arr = removeFirstTwo(source);
console.log(arr);
console.log(source);
//We can also assign the first two to some variables as below
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
const [ a, b, ...arr] = list;
return arr;
}
const arr = removeFirstTwo(source);
console.log(arr);
console.log(source);
Use Destructuring Assignment to Pass an object as a Function's Parameters
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = (function() {
return function half({ max, min }) {
return (max + min) / 2.0;
};
})();
console.log(stats);
console.log(half(stats));
Template Literals
function makeList(arr) {
const resultDisplayArray = [];
arr.forEach(element => resultDisplayArray.push(`<li class="text-warning">${element}</li>`))
console.log(resultDisplayArray)
return resultDisplayArray;
}
/**
* makeList(result.failure) should return:
* [ `<li class="text-warning">no-var</li>`,
* `<li class="text-warning">var-on-top</li>`,
* `<li class="text-warning">linebreak</li>` ]
**/
const resultDisplayArray = makeList(result.failure);
Write concise Object Literal Declaration uisng simple fileds
//LOng approach
const createPerson = (name, age, gender) => {
return {
name: name,
age: age,
gender: gender
};
};
console.log(createPerson("Zodiac Hasbro", 56, "male"));
//Using concise approach:
const createPerson = (name, age, gender) => ({ name, age, gender });
console.log(createPerson("Zodiac Hasbro", 56, "male"));
Write Concise Declarative function
//Concise Way
const bicycle = {
gear: 2,
setGear(newGear) {
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
//Long form:
const bicycle = {
gear: 2,
setGear: function(newGear) {
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
Use class Syntax to define a constructor function
//Using old way
var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
console.log(zeus.targetPlanet)
//New approach
class SpaceShuttle {
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
var zeus = new SpaceShuttle('Jupiter');
console.log(zeus.targetPlanet)
//Another Example
function makeClass() {
class Vegetable {
constructor(name){
this.name = name;
}
}
return Vegetable;
}
const Vegetable = makeClass();
const carrot = new Vegetable('carrot');
console.log(carrot.name);
Using getter & setters to control an access to an object
class Book {
constructor(author) {
this._author = author;
}
// getter
get writer(){
return this._author;
}
// setter
set writer(updatedAuthor){
this._author = updatedAuthor;
}
}
//Another Example
function makeClass() {
class Thermostat {
constructor(temp) {
this._temp = 5/9 * (temp - 32);
}
get temperature(){
return this._temp;
}
set temperature(updatedTemp){
this._temp = updatedTemp;
}
}
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76);
let temp = thermos.temperature;
thermos.temperature = 26;
temp = thermos.temperature;
Use export to reuse a code block
const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString };
export const foo = "bar";
export const bar = "foo";
Use * to import everything from a file
import * as capitalizeStrings from "capitalize_strings"
Create an Export fallback with export default
export default function subtract(x,y) {return x - y;}
Importing a Default Export
import subtract from "math_functions";
Throwing an error:
throw new Error('Title of the homepage should be "Conduit"');