Search code snippets, questions, articles...

javascript code snippets

JS Snippet
new Promise((resolve, reject) => {
  // asynchronous operation

  // then in case of success
  resolve();
  // or
  reject("failure reason");
});
Remove an object from array by value in Javascript
// define an array of objects
const students = [
    { id: 1, name: "Robin" },
    { id: 2, name: "Miller" },
    { id: 3, name: "John Deo" },
    { id: 4, name: "Troy" }
];

// find index of object which has id - 3
const index = students.findIndex(el => el.id === 3);

// remove the object
if (index >= 0) {
    students.splice(index, 1);
}

console.log(students);
Check if string includes a substring Javascript (Multiple Methods)
const str = "Devsheet";
const subStr = "evs";

if (str.includes(subStr)) {
    console.log("Included");
} else {
    console.log("Not included");
}
Filter an Array using object key value in Javascript
const students = [
    { id: 1, name: "John", marks: 91 },
    { id: 2, name: "Sumesh", marks: 89 },
    { id: 3, name: "Rick", marks: 78 },
    { id: 3, name: "Monty", marks: 93 }
];

const filtered_students = students.filter(item => item.marks > 90);

console.log(filtered_students);
Transform number to pattern "XXX XXX XXX"
function numberWithSpaces(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}
Using regex to validate a phone number in Javascript
function is_number_valid(val) {
    const re = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
    return re.test(val);
}

console.log("01234567890: " + is_number_valid("01234567890")); // true
console.log("123-456-7890: " + is_number_valid("123-456-7890")); // true
console.log("123.456.7890: " + is_number_valid("123.456.7890")); // true
console.log("123 456 7890: " + is_number_valid("123 456 7890")); // true
console.log("(123) 456 7890: " + is_number_valid("(123) 456 7890")); // true
console.log("1: " + is_number_valid("1")); // false
Javascript examples to remove url from a string
const url = "We have https://www.devsheet.com/my-example/ as a url";

const result = url.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');

console.log("result is: ", result);
Find the Third Smallest Number in an Array using Javascript
const numbers = [5, 9, 6, 3, 7, 5, 1, 2, 4];

numbers.sort(function (a, b) { return a - b });

console.log("Third smallest number: " + numbers[2]);
Send Form Data in axios POST request
var formData = new FormData();

formData.append('firstname', 'John');
formData.append('lastname', 'Deo');

axios({
    method: "post",
    url: "/url/to/api/",
    data: formData,
    headers: { "Content-Type": "multipart/form-data" },
})
.then(response => {
    console.log(response);
})
.catch(response => {
    console.log(response);
});
Optional params
...(categoryId ? {categoryId: categoryId} : {}),
Select Multiple Items
const setSubCatModalItem = item => {
 const array = selectedSubCat.map((val, ind) =>
   val.id === item.id ? {...val, isSelected: !val.isSelected} : {...val},
 );
 
 setSelectedSubCat(array);
};
Sort array of objects by key value in Javascript
const subjects = [
    { "name": "Math", "score": 81 },
    { "name": "English", "score": 77 },
    { "name": "Chemistry", "score": 87 },
    { "name": "Physics", "score": 84 }
];

// Sort in ascending order - by score
subjects.sort( (a,b) => a.score - b.score );

console.log(subjects);
Simplest Way to Find the Smallest Number in an Array using JavaScript
const arr = [5, 9, 8, 2, 6, 4, 7, 3, 13];

const min_val = Math.min(...arr)

console.log(min_val)
JS console function
function test() {
    console.log("test function");
}
Check if array contains duplicate values in Javascript
function check_duplicates(arr) {
    return new Set(arr).size !== arr.length;
}

console.log(check_duplicates([10, 20, 30, 40, 10]));
// -> true

console.log(check_duplicates([30, 50, 10, 40, 90]));
// -> false
Find the index of Max value in an array using Javascript
// create an array
const arr = [30, 20, 50, 70, 10, 40, 17];

// find the index of Max value
const max_index = arr.indexOf(Math.max(...arr))

console.log("Max value index is: ", max_index);
Access object properties using with() function in Javascript(ES6)
const user = {
    id: 10,
    name: 'Ankit',
    loc: 'India'
}

with (user) {
    console.log(name);
    console.log(loc)
}
Javascript to split string into array of characters
str = "Devsheet";

const arr = [...str];

console.log(arr)

// Output
// ["D","e","v","s","h","e","e","t"]
Run a Javascript file in Terminal window
// Create a JS file - script.js and put below code
function sum(a, b) {
    console.log(a + b);
}

sum(5, 10);

// run below command
// -> node script.js
Get text before @ in an email using Javascript
const email = "[email protected]"

const result = email.substring(0, email.indexOf("@"));

console.log(result);
Javascript function to get cookie value by name
function get_cookie(cookie_name) {
    let c_name = cookie_name + "=";
    let cookie_decoded = decodeURIComponent(document.cookie);
    let cookie_parts = cookie_decoded.split(';');
    
    for(let i = 0; i <cookie_parts.length; i++) {
        let c = cookie_parts[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(c_name) == 0) {
            return c.substring(c_name.length, c.length);
        }
    }
    return "";
}
Remove all cookies from the current website using Javascript
function clear_all_cookies() {
    var all_cookies = document.cookie.split(";");

    for (var i = 0; i < all_cookies.length; i++) {
        var single_cookie = all_cookies[i];
        var cookie_index = single_cookie.indexOf("=");
        var cookie_name = cookie_index > -1 ? all_cookies.substr(0, cookie_index) : single_cookie;
        document.cookie = cookie_name + "=;expires=" + new Date().toUTCString();
    }
}
Show confirmation alert before submitting a form in Javascript
document.getElementById("my_form").addEventListener("submit", function() {
   if (confirm("Are you sure to submit")) {
      return true;
   } else {
      return false;
   }
});
default test block for Mocha+Chai
describe("Название блока", function() {
  describe("название подблока", function() {
    it("Что проверяем?", function(){
      assert.isTrue(true)
    });
  });
});
Get number of keys in an object Javascript
const my_object = {"name": "Rick", "occupation": "Engineer", "city": "Atlanta"};

const number_of_keys = Object.keys(my_object).length;

console.log(number_of_keys);
Remember previously entered data in an input field using local storage in Javascript
function save_data_to_localstorage(input_id) {
   const input_val = document.getElementById(input_id).value;
   localStorage.setItem(input_id, input_val);
   console.log(input_val);
}


input_txt_1.addEventListener("keyup", function() {
   save_data_to_localstorage("input_txt_1");
});

input_txt_2.addEventListener("keyup", function() {
   save_data_to_localstorage("input_txt_2")
});

function init_values() {
   if (localStorage["input_txt_1"]) {
      input_txt_1.value = localStorage["input_txt_1"];
   }
   
   if (localStorage["input_txt_2"]) {
      input_txt_2.value = localStorage["input_txt_2"];
   }
}

init_values();
Create dummy APIs using json-server node module
// Sample json db file
{
    "users": [
        {
            "id": 100,
            "name": "John"
        }
    ]
}
Check if Array includes String(Case Insensitive) Javascript
const companies = ["Microsoft", "Apple", "Tesla", "Amazon", "Devsheet"];
const company =  "amazon";

const result = companies.findIndex( item =>  company.toLowerCase() === item.toLowerCase());

console.log(result);

// -> 3
Join two arrays and remove duplicate elements using Javascript
const arr1 = [10, 20, 30, 40, 50];
const arr2 = [40, 50, 60, 70, 80];

// concatenate the above arrays using spread operator
const join_arr = [...arr1, ...arr2];
console.log(join_arr);

// remove duplicate from above array using Set() function
const result = [...new Set(join_arr)];
console.log(result);
Check if a number is odd or even using Javascript
const value = 6;

const is_even = value % 2 == 0;

if (is_even) {
    console.log("Value is an even number");
} else {
    console.log("Value is an odd number");
}
Pass a function as parameter of another function in Javascript
function message() {
    return "Devsheet";
}

function print_message(my_function) {
    var msg = my_function();

    console.log(`Hello from ${msg}`);
}

print_message(message);
Remove all whitespaces from a string using javascript
// define a string with multiple whitespace
const str = "     Programming Is    Fun    ";

// remove whitespace using regex
const result = str.replace(/s/g, '');

// print the result
console.log(result);
Remove a key or property from Object in Javascript
// Define an object
const employee = {
    "name": "John Deo",
    "department": "IT",
    "project": "Inventory Manager"
};

// Remove a property
delete employee["project"];

console.log(employee);
Validate a url using regex in Javascript
function validate_url(url) {
    const url_regex = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)[email protected])?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i;

    return url_regex.test(url);
}

console.log( validate_url("invalidurl.com") );
// -> false

console.log( validate_url("http://validurl.com") );
// -> true
Add months to a date in Javascript
const my_date = new Date();
console.log(my_date);

// Add 3 months to today's date
new Date(my_date.setMonth(my_date.getMonth() + 3));

console.log(my_date);
Add a CSS class to element if dark mode is enabled using Javascript
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.getElementsByTagName("body")[0].classList.add("dark");
}
Check if dark mode is enabled using Javascript
const dark_mode_enabled = () =>
    window.matchMedia &&
    window.matchMedia("(prefers-color-scheme: dark)").matches;

console.log(dark_mode_enabled());
Methods to shuffle an array using javascript
function random_array(arr) {
    let idx = arr.length, random_num;

    while (idx != 0) {
        random_num = Math.floor(Math.random() * idx);
        idx--;

        [arr[idx], arr[random_num]] = [
            arr[random_num], arr[idx]];
    }

    return arr;
}

// Test the code
const result = random_array([10, 20, 30, 40, 50]);

console.log(result);
Remove duplicate items from array in Javascript
let numbers = [1, 3, 1, 5, 4, 3, 5];

numbers = numbers.filter(function (item, index) {
    return numbers.indexOf(item) == index;
});

console.log(numbers)
Javascript to get the number of days between two dates
const date_a = new Date("09/18/2021");
const date_b = new Date("10/20/2021");

const delta = date_b.getTime() - date_a.getTime();

const num_of_days = delta / (1000 * 60 * 60 * 24);

console.log("Number of days: " + num_of_days);
Get current timestamp in javascript
const timestamp = new Date().getTime();

console.log(timestamp);
Javascript to convert all object keys to lowercase
let person = {
    "Name": "Richard",
    "Company": "Pied Pieper",
    "Algo Name": "Compression"
};

let key, keys = Object.keys(person);
let total = keys.length;

let result = {}

while (total--) {
    key = keys[total];
    result[key.toLowerCase()] = person[key];
}

console.log(result);
Set a cookie that never expires using Javascript
document.cookie = "cookie_name=cookie_val; expires=Fri, 31 Dec 9999 21:10:10 GMT";
Set a cookie for whole domain in javascript
document.cookie = "cookie_name=cookie_value;path=/";
Count the total number of characters in a textarea while typing in javascript
const textarea = document.getElementById('textarea');
const show_counter = document.getElementById('show_counter');
const max_length = textarea.getAttribute('maxlength');

textarea.addEventListener('input', function (e) {
    const counts = this.value.length;
    show_counter.innerHTML = `${counts}/${max_length}`;
});
Javascript to run a function after script file is loaded
function load_script_file( file_url, callback ) {
  var script = document.createElement( "script" )
  script.type = "text/javascript";
  if(script.readyState) { // If browser(IE) is < 9
    script.onreadystatechange = function() {
      if ( script.readyState === "loaded" || script.readyState === "complete" ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    script.onload = function() {
      callback();
    };
  }

  script.src = file_url;
  document.getElementsByTagName( "head" )[0].appendChild( script );
}


// load script file and run the callback function 
load_script_file('script_file_path', function() {
    console.log("Script file is loaded");
});
Event System - Sigma Computing - 12/22/21
/*

We'd like to build an event system. It should have the following methods:

* on(eventName, listener) adds the listener for eventName and does not resolve the duplicates;
* off(eventName, listener) removes the listener for eventName if such combination exists;
* emit(eventName) invokes all event listeners of eventName.
* clear()

once(eventName, listener)
*/

let events = {}; // [{ listener: (){}, isOnce: boolean }]

// register the listener twice; don't need to detect if already exists
function on(eventName, listener) {
  const event = {
    listener,
    isOnce: false 
  }
  
  if (events[eventName]) {
    events[eventName].push(event); 
  } else {
    events[eventName] = [event]; 
  }
}

function off(eventName, listener) {
  if (events[eventName]) {
    events[eventName] = events[eventName].filter((registeredListenerObj) => {
      const registeredListener = registeredListenerObj.listener
      
      return registeredListener !== listener
    })
  }
  // TODO: Do we want to delete the key if there are no more listeners
}

function emit(eventName) {
  if (events[eventName]) {
    events[eventName].forEach((registeredListener) => { 
      const listener = registeredListener.listener
      const isOnce = registeredListener.isOnce
      
      listener();
      
      console.log("listener", listener)
      console.log("isOnce", isOnce)
      if (isOnce) {
        off(eventName, listener);
      }
    });
  }
}

function clear() {
  events = {};
}


function once(eventName, listener) {
  const event = {
    listener,
    isOnce: true
  };
  
  if (events[eventName]) {
    events[eventName].push(event); 
  } else {
    events[eventName] = [event]; 
  }
}



const listener = () => {
  console.log("eventName listener");
}

const secondListener = () => {
  console.log("second eventName listener");
}

// on("eventName", listener)
// on("eventName", listener)
// console.log(events)
// on("eventName", secondListener)
// console.log(events)
// on("second eventName", listener)
// console.log(events)

// emit("eventName")
// emit("second eventName")
// emit("does not exist")

// off("eventName", listener)
// console.log("off", events)
// off("eventName", listener)
// console.log("off", events)
// off("second eventName", listener)
// console.log("off", events)
// off("does not exist", listener)
// console.log("off", events)


// emit("eventName")
// emit("second eventName")

// clear()
// console.log("clear", events)
// emit()

// on("eventName", listener)
// console.log(events)

once("eventName", listener);
console.log(events)
emit("eventName")
console.log(events)
Methods to check empty array using javascript
// First method
const my_array = []

if (Array.isArray(my_array) && my_array.length) {
    //Array is not empty
} else {
    // Array is empty
}

// Second Method
if (my_array !== undefined && my_array.length > 0) {
    // Do somethong
}
Parenthesis Validation, Max Depth and Max Breadth - Braze - Full Stack - 12/20/21
// inputStr: May or may not contain paraentheses 
// valid: (()), check if valid expression
// some string // true
// (some string) // true
// ((some) string // false
// (() ())
// )))
// valid if no unbalanced set of parentheses
function hasValidParens(inputStr) {
    const parens = [];
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            const lastParens = parens.pop()
            if (typeof lastParens == 'undefined') {
                return false; 
            }
        }
    }
    
    return parens.length === 0; 
}


//console.log(hasValidParens("()")); // true
//console.log(hasValidParens("some string")); // true
//console.log(hasValidParens("(some string)")); // true 
//console.log(hasValidParens("((some) string")); // false 
//console.log(hasValidParens("(() ())")); // true
//console.log(hasValidParens(")))")); // false
//console.log(hasValidParens("(((")); // false


// maxDepth: (()) 2 
// ((), ()) 2
// ((), (())) 3
// Assume that it's valid 

function maxDepth(inputStr) {
    const parens = []; 
    let maxDepth = 0; 
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            if (parens.length > maxDepth) {
                maxDepth = parens.length;
            }
            parens.pop()
        }
    }
    
    return maxDepth;
}

//console.log(maxDepth("(())")); // 1
//console.log(maxDepth("((), ())")); // 2
//console.log(maxDepth("((), (()))")); // 2
//console.log(maxDepth("((()), ())")); // 2
// ()()(()()) // 3

// maxBreadth 

function maxBreadth(inputStr) {
    const parens = []; 
    let maxBreadth = 0; 
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            parens.pop();
            
            if (parens.length === 0) {
                maxBreadth++;
            }
            
        }
    }
    
    return maxBreadth;
}

console.log(maxBreadth("(())")); // 1
console.log(maxBreadth("((), ())")); // 2
console.log(maxBreadth("((), (()))")); // 2
console.log(maxBreadth("((()), ())")); // 2
console.log(maxBreadth("()()(()())")); // 3
Replace multiple spaces between words with single space using javascript
//Remove spaces along with tab spaces, new lines
const input_str = "Have   you   seen    spaces   here.";
const result_str = input_str.replace(/\s\s+/g, ' ');
console.log(result_str);
// -> Have you seen spaces here.
LRU Cache - Alphasights - Search and Discovery - Full Stack - 12/15/21
// Implement an LRU (Least recently used) cache

// Let T be the total possible page numbers that can be referred. Let N be the total number of page frames that the cache can hold at any time. The LRU caching scheme is to remove the least recently used frame when the cache is full and a new page is referenced which is not there in cache.

// Example:

// Consider the following sequential reference string, with N = 3:

// 1, 2, 3, 4, 2, 5, 1, 2, 3, 4, 5


// First we put 1,2 and then 3 into the cache. When 4 is referenced, it causes a fault since the cache is full but 4 is not in the cache. We eject 1 (the least recently used) resulting in 2, 3 and 4 in the cache. When page 2 it is in the cache, so the contents of the cache do not change. When 5 is referenced, it is not in the cache, so it causes another fault, so 3 gets ejected leading to 4, 2 and 5 being in the cache. Etc.

class lruCache {
    constructor(n) {
        this.n = n;
        this.cache = [];
        this.map = {};
    }
    
    eject(value) {
       //this.map[value] = null; 
       //this.map.remove(value);

        delete this.map[this.cache.shift()];
    }
    
    put(value) {
        if (this.map[value] != null) {
            return;
        } else {
             if (this.cache.length >= cacheSize) {
                this.eject(value);
            }
    
            this.cache.push(value);
            this.map[value] = true; 
        }
       
    }
    
    // get cache() {
    //     return this.cache;
    // }

}

const cacheSize = 3; 
// const cache = [];

// function eject() {
    
// }

// function put(value) {
//     if (cache.length >= cacheSize) {
//          eject();
//     }
    
//     cache.push(value);
// }

const input = [1, 2, 3, 4, 2, 5, 1, 2, 3, 4, 5]
function main(insertValues) {
    let cache = new lruCache(cacheSize);
    
    insertValues.forEach((insertValue) => {
        cache.put(insertValue);
        console.log(cache.cache);
        //console.log(cache.map)
    })
}

main(input);
Join array items and convert to string in javascript
const names = ["Rick", "Grimes", "Carol", "Alicia"];

//Join with default sepearor ,
name_str_1 = names.join();
console.log(name_str_1);
// -> Rick,Grimes,Carol,Alicia

//Jon with space seperator
name_str_2 = names.join(" ");
console.log(name_str_2);
// -> Rick Grimes Carol Alicia
Test every item of array against some condition in javascript
const scores = [86, 70, 56, 52, 78, 83];

const is_passed = scores.every( score => score > 33 );

console.log(is_passed);
// -> true
Convert a string to array using Array.from() in javascript
const str = "Hello";

const arr = Array.from(str);
console.log(arr);
// -> ["H","e","l","l","o"]
Search and Display Charities - Free Will - Nonprofit Gifts - Full Stack - 12/8/21
/*
  SHAPE REFERENCE

  interface Charity {
 	id: number;
 	name: string;

   // "Environment", "Education", or "Health"
 	category: string;
 	
	// if prime featureship, show amongst "Suggested" programs.
	isPrimeFeatureship: boolean;
  }

	ex:
	{
		id: 10,
		name: "Derek Zoolander Center",
		category: "Education",
		isPrimeFeatureship: true
	}
*/

/**
	Given a list of charities, return items to display in grid.
	
	Criteria:
	- Should match the header's selected category; "Suggested" shows prime featureships.
	- Should narrow results with the search, case insensitive.
	- Should sort alphabetically.

	params:
	charities: Charity[] - list of all charities
	activeCategory: string - the selected category
	searchString: string - the entered search string
*/
function getGridItems(charities, activeCategory, searchString) {
	console.log('searchStrin ', searchString)
	let filterFunction; 
	switch (activeCategory) {
		case "Suggested":
			filterFunction = (charity) => {
				return charity.isPrimeFeatureship
			}
			break;
		default: 
			filterFunction = (charity) => {
				return activeCategory == charity.category
			}
			break;
	}
	
	const filterCharities = charities.filter(filterFunction)
	const filteredSearchCharities = filterCharities.filter((charity) => {
		return charity.name.toLowerCase().includes(searchString.toLowerCase());
	})
	
	console.log('filteredSearchCharities', filteredSearchCharities)
	const sortedCharities = filteredSearchCharities.sort((charity1, charity2) => {
		if (charity1.name < charity2.name) {
			return -1;
		} else if (charity1.name < charity2.name) {
			return 1; 
		}
		return 0;
		// return charity1.name - charity2.name; 
	});
	// console.log('filterCharities', filterCharities)

	// placeholder for visualization
	return sortedCharities;
}

// charities from server. consider this synchronous.
const allCharities = getSeedCharities();

const CharityView = () => {
	// [value, setValue(new_value)] = React.useState(initial_value)
	const [activeCategory, setActiveCategory] = React.useState("Suggested");
	const [searchString, setSearchString] = React.useState("");

	const gridItems = getGridItems(allCharities, activeCategory, searchString);

	return (
		<div className="main">
			<Header />
			<CharityGridControls
				activeCategory={activeCategory}
				setActiveCategory={setActiveCategory}
				searchString={searchString}
				setSearchString={setSearchString}
			/>
			<CharityGridBody
				charities={gridItems}
				activeCategory={activeCategory}
				// carousel only, ignore
				onLeftClick={null}
				onRightClick={null}
			/>
		</div>
	);
};

/**
	-- IGNORE THIS -- 
	
	Part Two: Parent / Child programs
	
	Let's introduce two additional properties to the Charity shape.
	
	The first will be included and pre-filled in the server response:
	
	----
	parentProgramId: number
	----
	
	This property indicates the parent program of the child program.
	(ex 'Columbia University' is the parent program of 'Columbia School of Music')
	
	Only child programs will have this property defined.
	The parentProgramId will match the id of the parent charity.
	
	Ex:
	PARENT
	{
		(...)
		id: 10,
	}

	CHILD
	{
		(...)
		id: 11,
		parentProgramId: 10,
	}
	
	
	The second new property is:
	
	----
	childProgramCount: number
	----
	
	This indicates the number of child programs a program has.
	
	ex:
	{
		(...)
		id: 10,
		childProgramCount: 1,
	}
	
	This is NOT provided in the server response. Instead, modify your result from part 1 to:
	
	1. implement this childProgram count
	2. hide all child programs from the grid
	
*/

/**
	-- IGNORE THIS --
	
	Implement the carousel view.
	
	Requirements:
	
	- Shows up to 3 programs at a time.
	
	- Clicking a left/right control "skips" to a new set of 3 programs
	
	- The carousel should jump from the front to the back of the array if the user hits "left" from the first set, and vice versa for hitting "right" from the end.
		
		ex: 1, 2, 3 [LEFT] 13, 14, 15
		ex: 25, 26 [RIGHT] 1, 2, 3 
	
	<CharityGridBody /> above has two callback props for their respective arrows:
	
	onLeftClick
	onRightClick
*/
Microsoft Fill Paint - Bloomberg - Port Interactive Analytics - Full Stack - 12/6/21
// Start typing here

// image: 2d array iof numbers, grayscale 0 - 10 
// blank canvas, fills whole canvas
// function floodfill(image, xy, xz, tc)
// BFS, DFS to search 
// Add nodes/coordinates arounda  pixel (edge case)
// 0 0 0
// 1 1 0 // This shouldn't get filled 
// 0 0 1
//
/**
 * 0 0 0 0 0
   1 1 1 0 0
   0 0 0 1 0
   1 1 1 1 0
   0 0 0 0 0
   
   (1,2) --> (1,2), (0,2), (2,2)
   
   0 0 0 0 0
   1 1 1 0 0
   3 3 3 1 0
   1 1 1 1 0
   0 0 0 0 0
 * 
*/
Flexible UI Component - Bloomberg - Asset Management AIM - Full Stack - 12/6/21
// Start typing here

customers, not predefined properties 
properties displayed - for their customers 
all text based properties 
all properties are displayed the same way 
support different retailers - generic data store 

API to save the properties 
GET
update v. create v. PUT replacement
DELETE
security: Authorization Headers

merchant 
type of merchandise 

{
    retailer_id: 343,
    
    properties: [
        {
            itemType: id, 
            properties: {}
        }
    ]
        "type": { // id of type 
            "key": "value",
            "": {
            }
        }
    }
} 

// data storage 
merchants table (id, name)
itemTypes (id, name)
properties table (itemType - id, key, value)
Valid Dictonary String - Bloomberg - Port Interactive Analytics - Full Stack - 11/8/21
// Start typing here// Start typing here

// Given an input of a dictionary of words and an input string that does not contain spaces, write a method that returns a string with spaces inserted accordingly.

Input: "bloombergisfun", ["bloom","bloomberg","is","fun"]
Output: "bloomberg is fun"

// Returns the shorter matching string
"bloombergisfun", ["bloom",  "bloomberg","is","fun"]
"bloom berg is fun"

function spacedString(str, dictionary) {
    let currentStr = ''
    let words = [];
    
    for(let i = 0; i < str.length; i++) {
        currentStr ++ str[0]
        
        if (dictionary.has(currentStr)) {
            words.push(currentStr);
            currentStr = '';
        } 
    }
    
    return words.join(' ');
}
Sort Tree - Bloomberg - Port Interactive Analytics - Front End - 12/6/21
// Let's assume you are given the world tree, wherein the first level represents continents, the second level represents countries, the third level represents states/provinces and so on. Write a method to re-arrange this tree in such a way that all children of every node are sorted in alphabetical order.
     World
    / 
  North America
    /                        \
    US                       Canada
    /     \       \ 
California  NYC  Alabama

Node {
    value
    children: Node[]
}

Tree {
 topNode: Node
}

function sortChildren(tree) {


    // Continents 
    tree.topNode.children.sort((childNode1, childNode2) => {
        if (childNode1.value < childNode2.value) {
            return -1;
        } else (childNode1.value > childNode2.value) {
            return 1; 
        }
        return 0;
    })
    
    tree.topNode.children.foreach((continent) => {
        continent.children.foreach((country) => {
            country.children.foreach((state) => {
                
            })
        })
    });
}

function sort(node) {
    if (node.children) {
        node.children.foreach(() => { sort(node)}))
    } else {
        // reached the end 
    }
}
Batched Requests - AirTable - Automations - Front End - 12/3/21
/**
GET /read?keys=foo,bar

Response:
{
    "foo": 12,
    "bar": 42
}

Implement a function getKey(key) which fetches the specified key
and returns its value asynchronously to the caller.

The function signature is a starting point. Feel free to wrap it
in a class or add additional arguments if needed.

Desired behavior:
If getKey is called multiple times in a small window of time,
there should be a single network request to fetch all the required
values. For example, if the below 3 calls happen within a small window
of time, there should be a single network request:

getKey('foo', cb)
getKey('bar')
getKey('foo')
*/

const keys = new Set();
const keysToCallback = [];
let isFirstCall = true; 

function getKey(key, callback: (data: number) => void) {
    keys.add(key);
    keysToCallback.push({
        key, callback
    }); 
    //const keyPromise = new Promise();
    
    if (isFirstCall) {
        setTimeout(() => {
            $.ajax({
                path: '/read?keys=' + [...keys].join(',')
            }).then((values) => {
                //keyPromise.resolve(keysAndValues);    
                // Object.keys
                keysToCallback.foreach((value) => {
                    [key, callback] = value
                    callback(values[key])
                })
            }, () => {
                // Log 
                 
            });
            isFirstCall = true; 
        }, 1000);
        
        isFirstCall = false;
    }
    
    // keyPromise.then((values) => {
    //     return values[key];
    // });
}
Name Matching - Checkr - Adjudication - Full Stack - 11/19/21
/******************
 * Name Matching
 *
 *   At Checkr, one of the most important aspects of our work is accurately matching records
 * to candidates. One of the ways that we do this is by comparing the name on a given record
 * to a list of known aliases for the candidate. In this exercise, we will implement a
 * `nameMatch` method that accepts the list of known aliases as well as the name returned
 * on a record. It should return true if the name matches any of the aliases and false otherwise.
 *
 * The nameMatch method will be required to pass the following tests:
 *
 * 1. Exact match
 *
 *   knownAliases = ["Alphonse Gabriel Capone", "Al Capone"]
 *   nameMatch(knownAliases, "Alphonse Gabriel Capone") => true
 *   nameMatch(knownAliases, "Al Capone")               => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => false
 *
 *
 * 2. Middle name missing (on alias)
 *
 *   knownAliases = ["Alphonse Capone"]
 *   nameMatch(knownAliases, "Alphonse Gabriel Capone") => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => true
 *   nameMatch(knownAliases, "Alexander Capone")        => false
 *
 *
 * 3. Middle name missing (on record name)
 *
 *   knownAliases = ["Alphonse Gabriel Capone"]
 *   nameMatch(knownAliases, "Alphonse Capone")         => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => false
 *   nameMatch(knownAliases, "Alexander Capone")        => false
 *
 *
 * 4. More middle name tests
 *    These serve as a sanity check of your implementation of cases 2 and 3
 *
 *   knownAliases = ["Alphonse Gabriel Capone", "Alphonse Francis Capone"]
 *   nameMatch(knownAliases, "Alphonse Gabriel Capone") => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => true
 *   nameMatch(knownAliases, "Alphonse Edward Capone")  => false
 *
 *
 * 5. Middle initial matches middle name
 *
 *   knownAliases = ["Alphonse Gabriel Capone", "Alphonse F Capone"]
 *   nameMatch(knownAliases, "Alphonse G Capone")       => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => true
 *   nameMatch(knownAliases, "Alphonse E Capone")       => false
 *   nameMatch(knownAliases, "Alphonse Edward Capone")  => false
 *   nameMatch(knownAliases, "Alphonse Gregory Capone") => false
 *
 *
 * Bonus: Transposition
 *
 * Transposition (swapping) of the first name and middle name is relatively common.
 * In order to accurately match the name returned from a record we should take this
 * into account.
 *
 * All of the test cases implemented previously also apply to the transposed name.
 *
 *
 * 6. First name and middle name can be transposed
 *
 *   "Gabriel Alphonse Capone" is a valid transposition of "Alphonse Gabriel Capone"
 *
 *   knownAliases = ["Alphonse Gabriel Capone"]
 *   nameMatch(knownAliases, "Gabriel Alphonse Capone") => true
 *   nameMatch(knownAliases, "Gabriel A Capone")        => true
 *   nameMatch(knownAliases, "Gabriel Capone")          => true
 *   nameMatch(knownAliases, "Gabriel Francis Capone")  => false
 *
 *
 * 7. Last name cannot be transposed
 *
 *   "Alphonse Capone Gabriel" is NOT a valid transposition of "Alphonse Gabriel Capone"
 *   "Capone Alphonse Gabriel" is NOT a valid transposition of "Alphonse Gabriel Capone"
 *
 *   knownAliases = ["Alphonse Gabriel Capone"]
 *   nameMatch(knownAliases, "Alphonse Capone Gabriel") => false
 *   nameMatch(knownAliases, "Capone Alphonse Gabriel") => false
 *   nameMatch(knownAliases, "Capone Gabriel")          => false
 */

function hasMiddleName(name) {
  let splitName = name.split(' ');
  
  return splitName.length === 3;
}

function nameWithoutMiddleName(name) {
  if (hasMiddleName(name) {
    return [splitName[0], splitName[2]].join(' ');
  } 

  return name
}


function nameWithMiddleInitial(name) {  
  if (hasMiddleName(name) {
    return [splitName[0], splitName[1][0], splitName[2]].join(' ');
  } else {
    return name
  }
}

function nameMatch(knownAliases, name) {
  // Implement me
  let hasExactMatch = knownAliases.includes(name);
  
  if (hasExactMatch) {
    return hasExactMatch;
  }
  
  // Find a match with the middle name missing on the provided name
  let hasFuzzyMiddleNameMatch = knownAliases.includes(nameWithoutMiddleName(name));
  if (hasFuzzyMiddleNameMatch) {
    return hasFuzzyMiddleNameMatch;
  }

  // Find a match with the middle name missing on the provided aliases
  let aliasWithoutMiddleName = knownAliases.map((alias) => nameWithoutMiddleName(alias))
  let hasFuzzyAliasMiddleNameMatch = aliasWithoutMiddleName.includes(name);
  if (hasFuzzyAliasMiddleNameMatch) {
    return hasFuzzyAliasMiddleNameMatch;
  }


  let hasMiddleInitialMatch = knownAliases.includes(nameWithMiddleInitial(name));
   if (hasMiddleInitialMatch) {
    return hasMiddleInitialMatch;
  }


  let aliaswithMiddleInitialName = knownAliases.map((alias) => nameWithMiddleInitial(alias))
  let hasAliasMiddleInitialNameMatch = aliaswithMiddleInitialName.includes(name);

  if (hasAliasMiddleInitialNameMatch) {
    return hasAliasMiddleInitialNameMatch;
  }
    
  
  return false;
}

/** Tests **/

function assertEqual(expected, result, errorMessage) {
  if (result !== expected) {
    console.log(errorMessage);
    console.log(`expected: ${expected}`);
    console.log(`actual: ${result}`);
    console.log('');
  }
}

function test() {
  let knownAliases;

  knownAliases = ["Alphonse Gabriel Capone", "Al Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Gabriel Capone"), "error 1.1");
  assertEqual(true,  nameMatch(knownAliases, "Al Capone"),               "error 1.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Francis Capone"), "error 1.3");

  knownAliases = ["Alphonse Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Gabriel Capone"), "error 2.1");
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Francis Capone"), "error 2.2");
  assertEqual(false, nameMatch(knownAliases, "Alexander Capone"),        "error 2.3");

  knownAliases = ["Alphonse Gabriel Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Capone"),         "error 3.1");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Francis Capone"), "error 3.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Edward Capone"),  "error 3.3");

  knownAliases = ["Alphonse Gabriel Capone", "Alphonse Francis Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Gabriel Capone"), "error 4.1");
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Francis Capone"), "error 4.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Edward Capone"),  "error 4.3");

  knownAliases = ["Alphonse Gabriel Capone", "Alphonse F Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse G Capone"),       "error 5.1");
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Francis Capone"), "error 5.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse E Capone"),       "error 5.3");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Edward Capone"),  "error 5.4");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Gregory Capone"), "error 5.5");

  knownAliases = ["Alphonse Gabriel Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Gabriel Alphonse Capone"), "error 6.1");
  assertEqual(true,  nameMatch(knownAliases, "Gabriel A Capone"),        "error 6.2");
  assertEqual(true,  nameMatch(knownAliases, "Gabriel Capone"),          "error 6.3");
  assertEqual(false, nameMatch(knownAliases, "Gabriel Francis Capone"),  "error 6.4");

  knownAliases = ["Alphonse Gabriel Capone"];
  assertEqual(false, nameMatch(knownAliases, "Alphonse Capone Gabriel"), "error 7.1");
  assertEqual(false, nameMatch(knownAliases, "Capone Alphonse Gabriel"), "error 7.2");
  assertEqual(false, nameMatch(knownAliases, "Capone Gabriel"),          "error 7.3");

  console.log('Test run finished')
}
test();
War - Affirm - Asset Management AIM - 11/18/21
/*
Part 1:

 * this is a two player card game
 * the game starts with a deck of 52 cards represented as
   unique integers [1...52]
 * the cards are randomly shuffled and then dealt out to both players evenly.
 * on each turn:
     * both players turn over their top-most card
     * the player with the higher valued card takes
       the cards and puts them in their win pile
       (scoring 1 point per card)
 * this continues until all the players have no cards left
 * the player with the highest score (number of cards in their win pile) wins.
    * if they have the same number of cards in their win pile, tiebreaker goes to the player with the highest card in their win pile.

Be able to play the game with N players.
An input to the game will now be a list of strings (of length N) indicating the player names.
The deck contains M cards of distinct integers.
It is not guaranteed M % N == 0. If there are leftover cards they should randomly be handed out to remaining players.
i.e. with 17 cards and 5 people: 2 people get 4 cards and 3 get 3 cards
For example the input: game(["Joe", "Jill", "Bob"], 5) would be a game between 3 players and 5 cards.
you should print the name of the player that won the game.
*/

process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
    input += chunk;
});
process.stdin.on("end", function () {
    // now we can read/parse input
    
    const shuffleArray = array => {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            const temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    
    let shuffledDeck = Array.from({length: 52}, (_, i) => i + 1);
    shuffleArray(shuffledDeck);
    
    shuffleArray(shuffledDeck);
    console.log('shuffledDeck', shuffledDeck);
    
    let player1Deck = shuffledDeck.slice(0, 26);
    let player2Deck = shuffledDeck.slice(27);
    
    console.log('player1Deck', player1Deck);
    console.log('player2Deck', player2Deck);

    let player1WinningDeck = [];
    let player2WinningDeck = [];

    while (player1Deck.length > 0 || player2Deck.length > 0) {
        let player1CurrentCard = player1Deck.pop();
        let player2CurrrentCard = player2Deck.pop();
        
        if (player1CurrentCard > player2CurrrentCard) {
            player1WinningDeck.push(player1CurrentCard);
            player1WinningDeck.push(player2CurrrentCard);
        } else {
            player2WinningDeck.push(player1CurrentCard);
            player2WinningDeck.push(player2CurrrentCard);
        }
    }

    if (player1WinningDeck.length > player2WinningDeck.length) {
        console.log('player 1 won with ' + player1WinningDeck.length + ' points');
    } else if (player1WinningDeck.length < player2WinningDeck.length) {
        console.log('player 2 won with ' + player2WinningDeck.length + ' points');
    } else { 
        let sortedPlayer1WinningDeck = player1WinningDeck.sort();
        let sortedPlayer2WinningDeck = player2WinningDeck.sort();
        
        let player1MaxCard = sortedPlayer1WinningDeck[sortedPlayer1WinningDeck.length - 1]
        let player2MaxCard = sortedPlayer2WinningDeck[sortedPlayer2WinningDeck.length - 1]
        if (player1MaxCard > player2MaxCard) {
            console.log('player 1 won with ' + player1WinningDeck.length + ' points with max card ' + player1MaxCard);
        } else {
            console.log('player 2 won with ' + player2WinningDeck.length + ' points with max card ' + player2MaxCard);
        }
    }
    
    function war(players, numCards) {
        let playerDecks = {};
        let winningDecks = {};
        
        let shuffledDeck = Array.from({length: numCards}, (_, i) => i + 1);
        shuffleArray(shuffledDeck);
        
        // shuffledDeck.length / player.length 
        
        players.map((player) => {
            playerDecks[player] = [];
            winningDecks[player] = [];
        });
        
        for (let i = 0; i < shuffledDeck.length; i++) {
            let playerIndex = i % player.length 
            
            playerDecks[players[playerIndex]].push(card);
        }
        
        
        let hasCard s = true
        
        while (playerDecks.length) {
            let playingCards = [];
            
            for (const [player, playerDeck] of Object.entries(playerDecks)) {
                if (playerDeck.length == 0) {
                    delete playerDecks.player
                }
                
                playingCards.push({
                    player: player,
                    card: playerDeck.pop()
                });
            }
            
            let sortedPlayingCards = playingCards.sort((firstEl, secondEl) => { firstEl.card - secondEl.card } )
            let winningCard = sortedPlayingCards[playingCards.length]
            
            winningDecks[winningCard.player] = playerDecks[winningCard.player].concat(playingCards.map(playingCard => playingCard.card));
        }
        
        
        
        let arrWinning = []
        for (const [player, playerDeck] of Object.entries(winningDecks)) {
            arrWinning.push({
                player: player, 
                deckLength: playerDeck.length
            })
        }
        
        
        arrWinning.sort((firstEl, secondEl) => { firstEl.deckLength - secondEl.deckLength } )
        let tiedWinners = arrWinning.reduce( (tiedWinners, arrWinner) => 
            if (arrWinner.deckLength == arrWinning[arrWinning.length.deckLength) {
                tiedWinners.push(arrWinner);
            }
        }, []);
        
        
        if (tiedWinners.length == 1) {
            
        } else {
            tiedWinners.map((tiedWinner) => {
                winningDecks[tiedWinner.player].sort()
            })
            winningCards = tiedWinners.reduce((winningCard, tiedWinner) => {
                winningDecks.length
                winningDecks[tiedWinner.player][winningDecks.length - 1]
            }, []).sort()
            winningCards[winningCards.length]
            
        }
        
        
    }
});
Array.find() - get the very first element satisfy a condition Javascript
const numbers = [50, 60, 70, 80];
const element = numbers.find(num => num > 50);
console.log(element);
// -> 60
Difference in Gift Values - Free Will - Nonprofit Gifts - Full Stack - 11/15/21
// Input:
//
// estateSize - the total value of a person's estate (similar to 'net worth')
// oldGifts - list of existing gifts a person is donating to charity
// newGifts - list of new/updated gifts a person is donating to charity
//
// {
//    nonProfit: string,
//    amount: number,
//    amountType: 'dollar' | 'percent'
// }
//
// Instructions:
//
// 1. Calculate the difference in total value between the new and old gifts in dollars
// New and old gift difference example:
// Old gift: 150
// New gift: 100
// Expected output: -50
//
// Part 1 expected output: -19500
//
// 2. Return the difference in total value between the new and old gifts by non-profit
//
// Expected output:
// {
//     'Planned Parenthood': 1000,
//     'Doctors Without Borders': -500,
//     'United Way': -50000,
//     'Red Cross': 30000
// }

const estateSize = 1000000;

const oldGifts = [
  {
    nonProfit: "Planned Parenthood",
    amount: 10,
    amountType: "percent",
  },
  {
    nonProfit: "Doctors Without Borders",
    amount: 1000,
    amountType: "dollar",
  },
  {
    nonProfit: "United Way",
    amount: 5,
    amountType: "percent",
  }];

const newGifts = [
  {
    nonProfit: "Planned Parenthood",
    amount: 10,
    amountType: "percent",
  },
  {
    nonProfit: "Planned Parenthood",
    amount: 1000,
    amountType: "dollar",
  },
  {
    nonProfit: "Doctors Without Borders",
    amount: 500,
    amountType: "dollar",
  },
  {
    nonProfit: "Red Cross",
    amount: 3,
    amountType: "percent",
  }];

function giftTotal(estateSize, gifts) {
  let giftTotal = 0;
  for (let i = 0; i < gifts.length; i++) {
    if (gifts[i].amountType == 'dollar') {
      giftTotal += gifts[i].amount;
    } else {
      giftTotal += (gifts[i].amount / 100) * estateSize;
    }
  }

  return giftTotal;
}

function calculateTotalDiff(estateSize, oldGifts, newGifts) {
  //todo
  let oldGiftTotal = giftTotal(estateSize, oldGifts);
  let newGiftTotal = giftTotal(estateSize, newGifts);

  return newGiftTotal - oldGiftTotal;
}

function total(estateSize, gift) {
  if (gift.amountType == 'dollar') {
    return gift.amount;
  } else {
    return (gift.amount / 100) * estateSize;
  }
}

function calculateDiffByNonProfit(estateSize, oldGifts, newGifts) {
  //todo
  let nonProfitToDiff = newGifts.reduce((nonProfitToDiff, newGift) => {
    let nonProfitCurrentTotal = nonProfitToDiff[newGift.nonProfit];
    if (nonProfitToDiff[newGift.nonProfit] != null) {
      nonProfitToDiff[newGift.nonProfit] += total(estateSize, newGift);
    } else {
      nonProfitToDiff[newGift.nonProfit] = total(estateSize, newGift);
    }

    return nonProfitToDiff;
  }, {});

  // return oldGifts.reduce((nonProfitToDiff, oldGift) => {
  //   let nonProfitCurrentTotal = nonProfitToDiff[oldGift.nonProfit];

  //   if (nonProfitToDiff[oldGift.nonProfit] != null) {
  //     nonProfitToDiff[oldGift.nonProfit] -= total(estateSize, oldGift);
  //   } else {
  //     nonProfitToDiff[oldGift.nonProfit] = -total(estateSize, oldGift);
  //   }
  // }, nonProfitToDiff);

  oldGifts.forEach((oldGift) => {
    let nonProfitCurrentTotal = nonProfitToDiff[oldGift.nonProfit];

    if (nonProfitToDiff[oldGift.nonProfit] != null) {
      nonProfitToDiff[oldGift.nonProfit] -= total(estateSize, oldGift);
    } else {
      nonProfitToDiff[oldGift.nonProfit] = -total(estateSize, oldGift);
    }
  })

  return nonProfitToDiff;
}

calculateTotalDiff(estateSize, oldGifts, newGifts);
calculateDiffByNonProfit(estateSize, oldGifts, newGifts);
Recommendations - Bloomberg - Port Interactive Analytics - Full Stack - 11/8/21
- Build a recommendation system
- Given the likes of users, and a list of a user's likes, give recommendations 
1 A B C D
2 DC D 
3 C D

likes: B C

Returns [D, A] in this specific order (because D has two likes, and A only has one)


function reccomendations(dataSet: string[][], likes: string[])
  // hashmap D: 2, A: 1
  let currentRecommendations = {};
  loop over data set to get each individual user's likes 
    let isMatch = true;
    let currentReccomendations= []
    loop over each individuals likes 
      if data set user like is in likes
        matches++
      else isMatch = false
    if (matches == likes.length) 
     // Found a user match 
     add diff of user matches (e.g. reccomendations to currentRecommendations)

  // return currentRecommendations as a an array in sorted order
Compressed String with Sort - C3 AI - CRM - Full Stack - 11/11/21
function compressedStr(input) {
  let compressedResult = input[0];
  let currentChar = input[0]
  let currentCount = 1
 
  for (let i = 1; i < input.length; i++) {
    if (currentChar == input[i]) {
      currentCount++;
    } else {
      compressedResult += currentCount;
      compressedResult += input[i];
 
      currentChar = input[i];
      currentCount = 1; 
    }
  }
 
  compressedResult += currentCount;
 
  return compressedResult;
}
 
console.log(compressedStr('aaaaaaaaaabbbbbjjjkklaa'));
 
function compressedSort(input) {
  let arr = []
  //[(a, 10), (b,5)] { char: 'a', count: '1'0 } 
  let currentChar = input[0];
  for (let i = 1; i < input.length; i++) {
    if (isCharacterALetter(input[i])) {
      
    } else {
      // Digit 
      
    }
  }
}
 
 
function isCharacterALetter(char) {
  return (/[a-zA-Z]/).test(char)
}
2D Array Path - C3 AI - CRM - Full Stack - 11/11/21
/*
You are given an NxN map where each cell consists of a non-negative integer value 
representing the height of the cell.
 
There is a player on the map that stands at the top-left cell. 
The player wants to get to the bottom-right cell. 
The player can only move up, down, left, or right. 
Also, the player can move between two cells if the absolute difference in height between them is less or equal to the player jump power.
 
Given a map and a player jump power, 
write a function that returns true if the player can reach the bottom right cell, 
or false otherwise.
 
0 1 1 3 4
3 4 2 0 1
2 2 2 4 3
1 3 4 3 1
1 2 1 1 0
 
jump Power = 3
0 1 1
    2
    2
    4
    1 1 0
    
jump power = 1
0 1 2
    2
2 2 2
1
1 2 1 1 0
 
*/

function hasPath(map, jumpPower) {
  let queue = [{
    x: 0,
    y: 0
  }]
  
  let visited = {};
               
  while (!queue.empty) {
    let position = queue.pop
    
    if (visited[(position.x, position.y]) {
      continue; 
    } else {
      if (position.y == map.length && position.x == map[0].length) {
      // reached the bottom right 
      return true;
    } else {
      let right = map[position.y][position.x + 1]
      
      let left = map[position.y][position.x - 1]
      
      if (position.y + 1 < map.length) {
        let bottom = map[position.y + 1][position.x]
        if (jumpPower + map[position.x][position.y] >= bottom) {
          queue.push({
            x: postion.x,
            y: position.y + 1
          });
        }
      }
      
      let top = map[position.y - 1][position.x]
      
      visited[(position.x, position.y)] = true
    }
    
    //if (map[positon.x][position.y])
  }
  
  return false; 
}
Reusable Components
import React  from "react";

const InputField = ({ value, label, name, placeholder, type, onChange }) => (
  <div className="form-group">
    {label && <label htmlFor="input-field">{label}</label>}
    <input
      type={type}
      value={value}
      name={name}
      className="form-control"
      placeholder={placeholder}
      onChange={onChange}
    />
  </div>
);

export default InputField;




import React, { useState } from "react";
import InputField from "../UI/InputField";

const AddProductForm = () => {
  const [inputValue, setInputValue] = useState({ name: "", price: "" });
  const { name, price } = inputValue;

  const handleChange = (e) => {
    const { name, value } = e.target;
    setInputValue((prev) => ({
      ...prev,
      [name]: value,
    }));
    console.log(inputValue);
  };

  return (
     <Form>
       <InputField
         type="text"
         value={name}
         placeholder="Product Name"
         label="Name"
         name="name"
         onChange={handleChange}
       />
       <InputField
         type="number"
         value={price}
         placeholder="Add Price"
         label="Price"
         name="price"
         onChange={handleChange}
       />
       <Button color="primary">Add</Button>{" "}
       <Button color="secondary">Cancel</Button>
     </Form>
  );
};

export default AddProductForm;
Array iteration with setTimeout() javascript
const persons = ['John', 'Rick', ' Carol'];

let delay = 0;
persons.forEach(function (person) {
    setTimeout(function () {
        console.log(person);
    }, 1000 + delay);
    delay += 1000;
});
Van Ecks Sequence - Bloomberg - Asset Management AIM - Full Stack - 11/5/21
// Van Eck is a sequence that has 3 properties:
//   - Starts with 0
//   - For each element, count the number of steps since it's last appeared. This number of steps becomes the next term
//   - If the element has not appeared before, the next term is 0

// Sequence: [0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, ...]
//           [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Problem: Given an index, define a function that returns the element in Van Eck's sequence at that index.

function vanEcksAtIndex(index) {
    let arr = [0];
    // Last index which the number as appeared 
    let lastAppeared = {0: 0};
    
    
    for (let i = 0; i < index; i++) {
        console.log('i', i)
        console.log('arr', arr)
        console.log('lastAppeared', lastAppeared)
        if (lastAppeared[arr[i]] != null) {
            // Element has appeared before
            arr.push(i - lastAppeared[arr[i]]);
        } else {
            // Element hasn't appeared before
            arr.push(0);
        }
        lastAppeared[arr[i]] = i;
    }
    
    return arr[index];
}

// arr = [0], lastAppeared = { 0: 0 }
// i = 0, arr = [0, 0], lastAppeared = { 0: 0 }
// i = 1, arr = [0, 0, 1], lastAppeared = { 0: 1 }

console.log(vanEcksAtIndex(9));
Javascript code to remove falsy value like null, undefined, false from array
const my_array = [10, false, null, "devsheet", undefined];
const filtered_array = my_array.filter(Boolean);
// -> [10,"devsheet"]
Real time text-to-speech converter using Javascript
var speech = new SpeechSynthesisUtterance();
var all_voices = speechSynthesis.getVoices();

speech.voice = all_voices[1];
speech.text = "Hello John. Welcome to Devsheet";

speechSynthesis.speak(speech);
Stop loop for some seconds in Javascript
//Using recursion function
var counter = 0;

function loop_func() {
    setTimeout(function () {
        console.log('Loop Iteration: ' + counter);
        if (counter < 4) {
            loop_func();
        }
        counter++;
    }, 2000); //Add delay here - 2000 = 2 seconds
}

// The loop will run 5 times
loop_func();
Get the day name from given date in Javascript
const date_str = "07/20/2021";
const date = new Date(date_str);
const full_day_name = date.toLocaleDateString('default', { weekday: 'long' });
// -> to get full day name e.g. Tuesday

const short_day_name = date.toLocaleDateString('default', { weekday: 'short' });
console.log(short_day_name);
// -> TO get the short day name e.g. Tue
Get year from given date using Javascript
const date = "2018-04-05";
const date_obj = new Date(date);
const year = date_obj.getFullYear();
// -> 2018

// OR The above code can be written in single line
new Date("2018-04-05").getFullYear()
// -> 2018
Get current year using Javascript Date getFullYear() method
const today_date = new Date();
const current_year = today_date.getFullYear();
// -> returns the current year
Check whether a checkbox is checked or not using Javascript only
var checkbox = document.getElementById("checkbox_id");

if (checkbox.checked) {
    console.log("Checkbox is checked");
} else {
    console.log("Checkbox is not checked");
}
Get month name from a date using javascript
const date_str = "2021-09-20";
const my_date = new Date(date_str);

//Get month name from date using .toLocaleString() method
const full_month_name = my_date.toLocaleString("default", { month: "long" });
// -> September

//Get month name from date using .getMonth() method
const month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const month_num = my_date.getMonth();
const month_name = month_names[month_num];
// -> September
Get the current month name using javascript
var today_date = new Date();

// Using toLocaleString(Ecmascript)
// Full month name
const full_month_name = today_date.toLocaleString('default', { month: 'long' });
console.log(full_month_name);
// -> October(Or the current month)

//Short month name
const short_month_name = today_date.toLocaleString('default', { month: 'short' });
console.log(short_month_name);
// -> Oct (Or the short version of current month)

//Using getMonth() method
const month_num = today_date.getMonth();
const all_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const current_month = all_months[month_num];
console.log(current_month);
// -> October (Or the curent month name)
Bind external value inside .map javascript
setFornecedorValue(){
    return this.userContext.getFornecedor().cnpjCpf; 
  }

  montarPedidos = (pedidos: any) => {
    const self = this;

    return pedidos.map(function (item: any) {  
      return {...item, cnpjFornecedor: self.setFornecedorValue() }; 
    });
  }

  montarPedidos(arrayValues);
Remove duplicates ids from object array
score = [
    {
        id:123,
        name:"Arun",
        point:"10"
    },
    {
        id:123,
        name:"Arun",
        point:"10"
    },
    {
        id:12233,
        name:"Arudfn",
        point:"11230"
    },
]


const unique_result = [...new Map(score.map((item) => [item['id'], item])).values()]
Assign items of arrays to multiple variable when creating it (Array Destructuring) Javascript(ES6)
//First code example
const [value_1, value_2, value_3] = ["item_1", "item_2", "item_3"]
console.log(value_1);
console.log(value_2);
console.log(value_3);

//Second code example
const [fruits, vegetables] = [
    [{"name": "Orange"}, {"name": "Grapes"}, {"name": "Banana"}],
    [{ "name": "Potato" }, { "name": "Onion" }, { "name": "Lady fingers" }]
];
console.log(fruits);
console.log(vegetables);
Check if given value is an array in Javascript
const arr = ['1', '2', '3'];
const str = 'Devsheet';

is_array = Array.isArray(arr);
console.log(is_array);

is_array = Array.isArray(str);
console.log(is_array);
Filter array
const list = [1,2,3,4,5]

const even_list = list.filter((accumulator,element)=>{
    return element % 2 == 0
})
How to Remove duplicate elements from array in JavaScript ?
//Method 1
// Defining a set of the cities
  let city = [
    "surat",
    "ahmedabad",
    "rajkot",
    "mumbai",
    "surat",
    "delhi",
    "ahmedabad",
    "anand",
  ];
  
  // For removing the duplicate values
  // we are using the Set() function
  let unique_city = [new Set(city)];
  
  // Printing the unique cities
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]

//Method 2

// Defining the unique cities from the above
  // array by using forEach loop
  let unique_city = [];
  city.forEach((c) => {
    if (!unique_city.includes(c)) {
      unique_city.push(c);
    }
  });
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]


//Method-3
var my_array = [5, 4, 7, 8, 9, 2, 7, 5, 4, 8, 7];
unique_array = my_array.filter((item, index, array) => array.indexOf(item) === index);
console.log("Unique Array is : " + unique_array);

//Method - 4
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const filteredArr = arr.reduce((acc, current) => {
  const x = acc.find(item => item.id === current.id);
  if (!x) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);


//Method - 5
//Here's another possibility using the Map class constructor and values method:
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const uniqueObjects = [...new Map(arr.map(item => [item.id, item])).values()]


//Method-6

		function removeDuplicates() {
			// Create an array of objects
			books = [
				{ title: "C++", author: "Bjarne" },
				{ title: "Java", author: "James" },
				{ title: "Python", author: "Guido" },
				{ title: "Java", author: "James" },
			];
			// Display the list of array objects
			console.log(books);
			// Declare a new array
			let newArray = [];
			// Declare an empty object
			let uniqueObject = {};
			// Loop for the array elements
			for (let i in books) {
				// Extract the title
				objTitle = books[i]['title'];
				// Use the title as the index
				uniqueObject[objTitle] = books[i];
			}
			// Loop to push unique object into array
			for (i in uniqueObject) {
				newArray.push(uniqueObject[i]);
			}
			// Display the unique objects
			console.log(newArray);
		}


  //Method-7
  function removeDuplicates() {
          // Create an array of objects
          books = [
              { title: "C++", author: "Bjarne" },
              { title: "Java", author: "James" },
              { title: "Python", author: "Guido" },
              { title: "Java", author: "James" },
          ];
          jsonObject = books.map(JSON.stringify);
          console.log(jsonObject);
          uniqueSet = new Set(jsonObject);
          uniqueArray = Array.from(uniqueSet).map(JSON.parse);
          console.log(uniqueArray);
}

//Method- 8
const arr = [
    {place: "here",  name: "x", other: "other stuff1" },
    {place: "there", name: "x", other: "other stuff2" },
    {place: "here",  name: "y", other: "other stuff4" },
    {place: "here",  name: "z", other: "other stuff5" }
]
function getUniqueListBy(arr, key) {
    return [...new Map(arr.map(item => [item[key], item])).values()]
}

//get unique by place
const arr1 = getUniqueListBy(arr, 'place');
//get unique by name
const arr2 = getUniqueListBy(arr, 'name')
Array reducce
//Reference ->  https://sebhastian.com/javascript-sum-array-objects/
//Sometimes, you need to count the sum of property in an array of objects. 
//For example, you may find an array of items, and you want to sum the total quantity a person must pay for the items
let cart = [
  {
    name: "JavaScript book",
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    price: 9,
  },
];
// totalPrice is 92
let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.price;
}, 0);


//Perform multiple operations before returning the data
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 215

let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.quantity * item.price;
}, 0);



//Filter the array before reduce
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 170

let totalPrice = cart
  .filter(
    (item) =>
      item.name === "JavaScript book" ||
      item.name === "UGG Women's Hazel Ankle Boot"
  )
  .reduce((accumulator, item) => {
    return accumulator + item.quantity * item.price;
  }, 0);
Regex for email validation in Javascript
function email_validator(my_email) {
    var email_pattern = /^(([^<>()[]\.,;:[email protected]"]+(.[^<>()[]\.,;:[email protected]"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    if (email_pattern.test(my_email)) {
        console.log("Email is Valid");
    } else {
        console.log("Email is Invalid");
    }
}

email_validator("[email protected]"); // -> logs - Email is Valid
email_validator("test.com"); // -> logs - Email is Invalid
Compress or minify JSON using Javascript
var json_str = `[
    {
      "type": "people",
      "id": "30",
      "attributes": {
        "name": "John Deo",
        "age": 40,
        "gender": "male"
      }
    }
]`;

var minified_json = JSON.stringify(JSON.parse(json_str));
console.log(minified_json);
Javascript Sort() By Multiple Criteria
const teams = [
    {name: "Aviso1", state: true, priority: 1},
    {name: "aviso3", state: true, priority: 3},
    {name: "Aviso2", state: false, priority: 2},
    {name: "aviso4", state: true, priority: 4},
    {name: "aviso5", state: false, priority: 5},
    {name: "aviso6", state: true, priority: 6}
]
let formated = teams.sort((a, b) => a.state === b.state ?  a.priority - b.priority : b.state - a.state);

console.log(formated)


/*
[
  { name: 'Aviso1', state: true, priority: 1 },
  { name: 'aviso3', state: true, priority: 3 },
  { name: 'aviso4', state: true, priority: 4 },
  { name: 'aviso6', state: true, priority: 6 },
  { name: 'Aviso2', state: false, priority: 2 },
  { name: 'aviso5', state: false, priority: 5 }
]*/
test113142
function hello() {
    return <h1>Hello world</h1>
}
Prettify JSON object or array using JSON.stringify
const json_data = {id: 10001, name: "Tokyo", show: "La Casa De papel"};
const pretty_json_str = JSON.stringify(json_data, undefined, 4);
Convert JSON data to String
const json_obj = { id: 1, name: "John Rick", pin: "000000" };
const json_str = JSON.stringify(json_obj);
Convert String to JSON Data
const str_data = '{"name": "Rick Grimes", "city": "New York","pincode": "000-000"}';

//Parse to json data
const json_data = JSON.parse(str_data);

//Using callback function in JSON.parse
const json_data2 = JSON.parse(str_data, function(key, value) {
    //DO something here
})
wait/delay function
method: {
    async function() {
        //first action
        await this.timeout(3000);//delay
        //second action
    },
    timeout(ms) {
        return new Promise(resolve => {
            window.setTimeout(resolve, ms)
        })
    }
}
Calculate square root of a number using javascript
const num = 100;
const sqrt = Math.sqrt(num);
Check if all array items are equal javascript
const allEqual = arr => arr.every(v => v === arr[0]);
allEqual([1,1,1,1]);  // true
Load or preview html to Iframe using Javascript only
var html = '';
html += '<!DOCTYPE html>\n';
html += '<html lang="en">\n';
html += '<head>\n';
html += '</head>\n';
html += '<body>\n';
html += '<div>Hello World we are here...</div>';
html += '</body>\n';
html += '</html>';

(document.getElementById("iframe_id").contentWindow.document).write(html);
(document.getElementById("iframe_id").contentWindow.document).close();
Get all values as array items from an Object in Javascript
const obj = {
    "id": 20,
    "name": "John Deo",
    "dept": "Computer",
    "pincode": "11111"
};

var obj_values = Object.values(obj);
Get all keys from an object using Javascript
var obj = {
    "name": "Ankit",
    "username": "ankit01",
    "status": "active",
    "contact": "mail"
};

var all_keys = Object.keys(obj);
Convert object {key: value} to Array [[key, value]] Javascript
const obj = { a: 1, b: 2, c: 3 };

const entries = Object.entries(obj);
Check if a string is Palindrome or not using Javascript
function palindrome_checker(str) {
    const converted_str = str.split('').reverse().join('');
    if (str === converted_str) {
        console.log(str + " : String is Palindrome");
    } else {
        console.log(str + " : String is not Palindrome");
    }
}

palindrome_checker('deified');
palindrome_checker('Ankit');
Convert a String to Number or Integer in Javascript
const str = "200";
var num = parseInt(str);
Swapping two values using Destructuring in Javascript
let a = 5;
let b = 8;
[a, b] = [b, a]

console.log([a, b])
Convert a Number or Integer to String in Javascript
const num = 10;
const str = num.toString();
Assign default values to function parameters in Javascript
const func = (arr, arg2 = 0, len = arr.length) => { // Here arg2 and len are parametes with default values.
    return len;
}
const result = func([10, 30, 40, 50, 60]);
console.log(result);
Combine or merge two or multiple arrays into single array in Javascript
const users1 = ['Ankit', 'Gaurav'];
const users2 = ['Abadhesh', 'Sourabh'];
const users3 = ['Arun', 'Avinash'];

//FIRST METHOD - using ...
const all_users1 = [...users1, ...users2, ...users3];

//SECOND METHOD - using .concat()
const all_users2 = users1.concat(users2).concat(users3)
Pass multiple arguments when calling a function which takes single argument Javascript
function func_name(...allArgs) {
    console.log("Paraameter at 3th position : " + arguments[2]);
    console.log("Paraameter at 6th position : " + arguments[5]);
}

func_name("value1", "value2", "value3", "value4", "value5", "value6");
Use of ?? (Nullish Coalescing Operator) in Javascript
const user_name = null ?? 'Ankit';
// Output: "Ankit"

const number = 0 ?? 40;
// Output: 0
Optional Chaining on Javascript Object
const user = {
  admin: {
    name: "John Deo"
  }
};
user.admin?.name;
// "John Deo"
user.admi?.name;
// undefined
user.admi.name
// TypeError: Cannot read property 'name' of undefined
Concatenate multiple objects into one using Javascript
const user = {
    name: 'John Deo',
    gender: 'Male'
};
const role = {
    admin: '1'
};
const details = {
    email: '[email protected]',
    city: 'New York',
};

const final_object = { ...user, ...role, ...details };

console.log(final_object);
How to use Ternary Operator in place of if else statements Javascript
//Simple If else condition using Ternary Operator
const score = 15;
const score_checker = score > 20 ? 'Score is grater than 20' : 'Score is less than 20';
console.log(score_checker);

//Nested If else conditions can be written using Ternary Operator
function check_number(num) {
    return num > 7 ? 'Number is greater than 7'
        : num < 7 ? 'Number is less than 7'
            : num === 7 ? 'Number is equals to 7' : "";
}

console.log(check_number(7));
console.log(check_number(6));
console.log(check_number(10));
Calculate the frequency of characters in a string using Javascript
const str = 'CoNgratulations';

const letters = {};
for (let char of str.toLowerCase()) {
    letters[char] = letters[char] + 1 || 1;
}

console.log(letters);
Remove duplicate values from an array in Javascript
var my_array = [5, 4, 7, 8, 9, 2, 7, 5, 4, 8, 7];

// First Method
unique_array = my_array.filter((item, index, array) => array.indexOf(item) === index);
console.log("Unique Array is : " + unique_array);

// Second Method
var another_uni_arr = [...new Set(my_array)];
console.log("Another Unique Array is : " + another_uni_arr);
Use of logical operators to reduce if else statements Javascript
function run_func(number) {
    // set number to 35 if it is not already set
    number = number || 35;
    console.log("Number is : " + number);
}

const check_this_var = 20;
check_this_var === 20 && run_func();
// SAME AS - if (check_this_var === 20) { run_func(); }
// Output: 10

check_this_var === 5 || run_func();
// SAME AS if (check_this_var != 5) { run_func(); }
// Output: 10
Remove empty, false, undefined values from array Javscript
var my_arr = [4, '', 0, 10, 7, '', false, 10];

my_arr = my_arr.filter(Boolean);

console.log(my_arr);
Get the sum of array values using Javascript - Solved
const myarr = [10, 23, 32, 65, 7, 24];
const sum_of_array = myarr.reduce((a, b) => a + b);
console.log(sum_of_array);
Find the maximum value from an array using Javascript
const myarr = [10, 23, 32, 65, 7, 24];
const max_value = myarr.reduce((a, b) => a > b ? a : b);
console.log(max_value);
Find the minimum value from an array javascript
const myarr = [10, 23, 65, 7, 24];
const min_val = myarr.reduce((a, b) => a < b ? a : b);
console.log(min_val);
Create fixed length array with blank values in it Javascript
var my_arr = Array(7).fill('');

console.log(my_arr);
rascunho
https://dev.to/techygeeky/top-20-javascript-tips-and-tricks-to-increase-your-speed-and-efficiency-283g
Run a Javascript function after user finished writing in the input field
var type_timer;
var finished_writing_interval = 3000;
var my_input = document.getElementById("my_input");

//Start timeout when user start typing
my_input.addEventListener('keyup', function () {
  clearTimeout(type_timer);
  type_timer = setTimeout(finished_typing, finished_writing_interval);
});

//Clear timeout on key down event
my_input.addEventListener('keydown', function () {
  clearTimeout(type_timer);
});

//This function runs when user has finished writing in input
function finished_typing () {
    console.log("User finished typing");
    //Do something here ...
}
Scroll to the bottom of a div using Javascript
var my_div = document.getElementById("my_div");
my_div.scrollTop = my_div.scrollHeight;
Run a function every 5 seconds interval using Javascript
var inverval_timer;

//Time in milliseconds [1 second = 1000 milliseconds ]    
inverval_timer = setInterval(function() { 
    console.log("5 seconds completed");
}, 5000);
    
//IF you want to stop above timer
function stop_timer() {
    clearInterval(inverval_timer); 
}
Remove new line separator from start and end positions of string in Javascript
my_str = "\n\n Hello World \n\n\n";
my_str = my_str.replace(/^\s+|\s+$/g, '');
console.log(my_str);
Order and find elements
carlist.map(element => 
console.log(element.brand +" = "+ element['models'].length )); 

console.log("result ==" + JSON.stringify(carlist.filter(element => element['brand'] ==  'Renault'),null,4)); 



var formatedlsit = []; 
var asceding = []; 
var desceding = []; 


formatedlsit = carlist.map(item => ({
        brand: item.brand,
        totalOfmodels: item.models.length
}));


console.log('--------------------------------------------------')

//console.log('formatedlist');
//console.log(JSON.stringify(formatedlsit, null, 4 ));

/*  asceding = formatedlsit.sort(function(a, b){return a.totalOfmodels - b.totalOfmodels});
desceding =  formatedlsit.sort(function(a, b){return b.totalOfmodels - a.totalOfmodels}); 
console.log('------------------ crescente--------------------------------')
console.log(JSON.stringify(asceding, null, 4 ));
console.log('-------------------decrescente-------------------------------')
console.log(JSON.stringify(desceding, null, 4 ));
console.log("mais modelos " + asceding[0].brand);
console.log("menos modelos" + desceding[0].brand);  */ 

 console.log(formatedlsit.sort(function(a, b){return a.totalOfmodels - b.totalOfmodels}));
console.log(formatedlsit.sort(function(a, b){return b.totalOfmodels - a.totalOfmodels}));
jquery linq
https://www.buildinsider.net/web/jqueryref/059
https://qiita.com/nishiurahiroki/items/5fe52bbcbb91d3181bbd#%E5%80%A4%E3%81%AE%E3%82%BB%E3%83%83%E3%83%88value
https://www.it-swarm-ja.tech/ja/jquery/1%E7%A7%92%E3%81%94%E3%81%A8%E3%81%ABajax%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%82%92%E5%AE%9F%E8%A1%8C%E3%81%99%E3%82%8B/1042450943/
Check if a variable is null, empty, undefined or false Javascript
if (variable_name) {
    //variable_name will not be null, empty, undefined or false
}
Editorjs blocks - JSON to HTML javascript
function jsonToHtml(jsonStr) {
    obj = JSON.parse(jsonStr);

    html = '';
    obj["blocks"].forEach(function(block, index) {
        switch (block['type']) {
            case 'paragraph':
                html += '<p>'+ block['data']['text'] +'</p>';
                break;
            
            case 'header':
                html += '<h'+ block['data']['level'] +'>'+ block['data']['text'] +'</h'+ block['data']['level'] +'>';
                break;

            case 'raw':
                html += block['data']['html'];
                break;

            case 'list':
                lsType = (block['data']['style'] == 'ordered') ? 'ol' : 'ul';
                html += '<' + lsType + '>';
                block['data']['items'].forEach(function(item, index) {
                    html += '<li>' + item + '</li>';
                });
                html += '</' + lsType + '>';
                break;
            
            case 'code':
                html += '<pre><code class="language-'+ block['data']['lang'] +'">'+ block['data']['code'] +'</code></pre>';
                break;
            
            case 'image':
                html += '<div class="img_pnl"><img src="'+ block['data']['file']['url'] +'" /></div>';
                break;
            
            default:
                break;
        }
    });
    
    return html;
}
Util Array Examples
const allLanguages = [ 'ES', 'EN', 'DE' ]
const usedLanguages = [ { id: 1, lang: 'EN' } ].map(e => e.lang);

var result = allLanguages.filter(e => !usedLanguages.includes(e));
console.log(result)


=================



 const myArrayFiltered = this.AllGroupActive.filter(array => this.workFrontAnomalyType.developmentStageGroupId.some(filter => filter === array.id ));
 const checkAllActive = myArrayFiltered.every(item => item.active);



 ===========================================================
var arr1 = ['a', 'b'];
var arr2 = ['a', 'b', 'c', 'd'];

  let intersection = arr1.filter(x => arr2.includes(x));
  let difference = arr1.filter(x => !arr2.includes(x));

   symmetric difference,

   let difference = arr1
                 .filter(x => !arr2.includes(x))
                 .concat(arr2.filter(x => !arr1.includes(x))); 
=======================

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

============

 removeAnomaly(anomaly: WorkFrontAnomaly){
        var index = this.workFrontAnomalies.indexOf(anomaly);

        if(index != -1){
            this.workFrontAnomalies.splice(index, 1);
        }
    }
Javascript Map and Filter together
data
    .filter(item => item.workFrontAnomalyTypeId === this.WorkFrontAnomalyTypeId)
    .map(anomaly => ({
        name: anomaly.name,
        id: anomaly.id,
        active: anomaly.active,
        workFrontAnomalyTypeId: anomaly.workFrontAnomalyTypeId,
        impedative: anomaly.impedative
    }));
For loop in Javascript
for (var i = 0; i < 5; i++) {
    console.log(i);
}
Get and set storage in chrome extension
chrome.storage.sync.set({name: value}, function() {
    console.log('value is : ' + value);
});

chrome.storage.sync.get(['name'], function(result) {
    console.log('name is : ' + result.name);
});
open link in new tab using javascript
window.open('https://devsheet.com', '_blank');
Remove item from array in Javascript
const myArray = [2, 5, 9];

const removeIndex = 2;

myArray.splice(removeIndex, 1);

console.log(myArray);
How to Check if Arrays in a Object Are All Empty
var allEmpty = Object.keys(obj).every(function(key){
return obj[key].length === 0
})

//filter 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).filter( function(key){
      return obj[ key ].length > 0;  //if any array has a property then filter will return this key.
    }).length == 0; //used == here since you want to check if all are empty
}

//every 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).every( function(key){
      return obj[ key ].length == 0;  
    }); 
}

//some 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).some( function(key){
      return obj[ key ].length > 0;  
    }) === false; 
}

//es8 
const objectIsEmpty = obj => Object.values(obj).every(
    val => Array.isArray(val) && val.length === 0
);

//every 2 sample 
function objectIsEmpty(obj) {
    return Object.keys(obj).every(key => 
      Array.isArray(obj[key]) && obj[key].length
    );
}
CODE GENERATOR
function makeid(length) {
   var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

console.log(makeid(5));
Truthy and Falsy in JavaScript
/*In JavaScript, truthy are expressions which evaluates to boolean true value and falsy evaluates to boolean false value. Unlike other languages, true and false values are not limited to boolean data types and comparisons. It can have many other forms. */


//Falsy Values
false
0 Both positive and negative
0n BigInt, when used as a boolean, follows the same rule as a Number
''
null
undefined
NaN
let a = false
    let b = 0
    let c = -0
    let d = 0n
    let e = ''
    let f = null
    let g = undefined
    let h = NaN
    console.log(Boolean (a))
    console.log(Boolean (b))
    console.log(Boolean (c))
    console.log(Boolean (d))
    console.log(Boolean (e))
    console.log(Boolean (f))
    console.log(Boolean (g))
    console.log(Boolean (h))

//Truthy Values
true
{} An object (whether empty or not)
[] An array (whether empty or not)
25 Numbers (whether positive or negative)
'true' Non empty strings
'false' Non empty strings
new Date() Date object
12n BigInt, when used as a boolean, follows the same rule as a Number
Infinity
JavaScript ES6 filtering object with multiple params
let equipmentsReturn = [
                { id: 23, typeId : 214 , groupId :10, tag:"CM0091"}, 
                { id: 11, typeId : 314 , groupId :10, tag:"CM009"}, 
                { id: 435, typeId : 412 , groupId :10, tag:"CM009"},
                { id: 23231, typeId : 2142312 , groupId :10, tag:"CM009"}, 
                { id: 1231231, typeId : 31444 , groupId :10, tag:"CM009"}, 
                { id: 48882, typeId : 412331 , groupId :10, tag:"CM009"},
                { id: 20, typeId : 12356734 , groupId :10, tag:"CM009"},
                { id: 31, typeId : 8888888 , groupId :10, tag:"CM009"},
                { id: 31236566, typeId : 100 , groupId :10, tag:"CM009"},
                { id: 31236566, typeId : 200 , groupId :10, tag:"CM009"}

            ];
            let arraytype = [214];
            let arraygroupId = [ 86, 77];
            let arraytag = ["CM119","CM977"];

            const filtered = equipmentsReturn.filter(({ typeId ,groupId , tag}) =>
            arraytype.includes(typeId) || arraygroupId.includes(groupId) || arraytag.includes(tag) );
            
           console.log(filtered);
Javascript Async/Await ES7
async function foo() {
    const myPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Parwinder"); // resolves with "Parwinder" after 2 seconds
        }, 2000);
    });

    // will not move to the next line until myPromise resolves/rejects
    const name = await myPromise;
    // the execution pauses (or awaits) for the promise

    console.log(name); // Parwinder
}

foo();
Get total sum of specif attribute inside of array of objects
let products = [{
  "id": 1,
  "product_name": "Forester",
  "price": 10
}, {
  "id": 2,
  "product_name": "Rainier",
  "price": 10
}, {
  "id": 3,
  "product_name": "Yukon Denali",
  "price": 10
}, {
  "id": 4,
  "product_name": "Regal",
  "price": 10
}, {
  "id": 5,
  "product_name": "Alcyone SVX",
  "price": 5
}];

let totalPrice = products.reduce((accumulator, current) => {
          return accumulator + current.price;
        }, 0);

//totalPrice 45
Find the shortest string in array
let arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce(function(a, b) {
    return a.length <= b.length ? a : b;
  })
)
// result a
Finding the max/min value of an attribute in an array of objects
//Mapping formated counting 
var arr = ['one', 'two', 'three']
arr.map(element => ({ valor : element.length, descricao: element}) );

//result of the code above and look like this array...
let array =[
    {
        "valor": 3,
        "descricao": "one"
    },
    {
        "valor": 3,
        "descricao": "twsso"
    },
    {
        "valor": 5,
        "descricao": "threexx"
    }
];

let maxvalue = Math.max.apply(Math,array.map(function(o){return o.valor;}))
let minvalue = Math.min.apply(Math,array.map(function(o){return o.valor;}))

let objmax = array.find(function(o){ return o.valor == maxvalue; })
let objmin = array.find(function(o){ return o.valor == minvalue; })

console.log("max word value" + JSON.stringify(objmax)); 
console.log("min word value" + JSON.stringify(objmin));
Get a bigger word from a javascript array
console.log(longestStringReduce(['boop', 'bloomburg', 'hello']));

function longestStringReduce(arr) {
  return arr.reduce((a, b) => a.length < b.length ? b : a, "");
}

//bigger word
//bloomburg
Get Top MAX and MIN itens inside array Javascript
var maxPoints = [];
var scoreByPattern = [93,17,56,91,98,33,9,38,55,78,29,81,60];

function cloneArray(array) {
    return array.map(function(i){ return i; });
}    
function max3(array) {
    return cloneArray(array).sort(function(a,b) { return b-a; }).slice(0,3);
}
function min3(array) {
     return cloneArray(array).sort(function(a,b) { return a-b; }).slice(0,3);
}

var array=scoreByPattern;
alert("Max:"+ max3(array)[0] +' '+max3(array)[1] +' '+max3(array)[2]);
alert("Min:"+ min3(array)[0] +' '+min3(array)[1] +' '+min3(array)[2]);
// Max:98 93 91
// Min:9 17 29

//Top 5 itens
scoreByPattern.sort((a, b) => b - a).slice(0, 5);
// [98, 93, 91, 81, 78]
Javascript ES6 Template strings
const name = 'Matheus'
const message = `Hello `

console.log(message) // prints "Hello Matheus"
Javascript ES6 Destructuring
const Person = {
  name: "John Snow",
  age: 29,
  sex: "male",
  materialStatus: "single",
  address: {
    country: "Westeros",
    state: "The Crownlands",
    city: "Kings Landing",
    pinCode: "500014",
  },
};

const { address : { state, pinCode }, name } = Person;

console.log(name, state, pinCode) // John Snow The Crownlands 500014
console.log(city) // ReferenceErro

//Extract especif information from objects array
let array = [ {"name":"Joe", "age":17, "sex":"M"},{"name":"Bob", "age":17, "sex":"M"},{"name":"Carl", "age": 35, "sex":"M"}];
let especifArrayAtributes = array.map(x => ({firstname: x.name, age : x.age}));
console.log(especifArrayAtributes); //"[{"firstname":"Joe","age":17},{"firstname":"Bob","age":17},{"firstname":"Carl","age":35}]"
Javascript ES6 Rest Parameters
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
Javascript ES6 Spread Operator
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1);
Javascript ES6 Array Filter
const allUsers = [{
        "name": "Zediane Araújo",
        "age": 66,
        "picture": "https://randomuser.me/api/portraits/thumb/women/13.jpg",
        "gender": "female"
    },
    {
        "name": "Nara Porto",
        "age": 70,
        "picture": "https://randomuser.me/api/portraits/thumb/women/77.jpg",
        "gender": "female"
    },
    {
        "name": "Ferafina da Cruz",
        "age": 66,
        "picture": "https://randomuser.me/api/portraits/thumb/women/3.jpg",
        "gender": "female"
    },
    {
        "name": "Cliseu Castro",
        "age": 48,
        "picture": "https://randomuser.me/api/portraits/thumb/men/24.jpg",
        "gender": "male"
    },
    {
        "name": "Aiara Cavalcanti",
        "age": 69,
        "picture": "https://randomuser.me/api/portraits/thumb/women/3.jpg",
        "gender": "female"
    }
];

const filteredUsers = allUsers.filter((user) => {
    const inputValue = "CLI"; //Obtenha valor do input com .value, deixei esse valor para exemplo 
    const valueFilterLower = inputValue.toLowerCase(); //convertendo valor do input para minisculo
    const lowername = user.name.toLowerCase(); // converta o nome atual para minisculo
    return lowername.indexOf(valueFilterLower) > -1; // O método indexOf() retorna o primeiro índice em que o elemento pode ser encontrado no array, retorna -1 caso o mesmo não esteja presente.
    //lembrando que O método filter() cria um novo array com todos os elementos que passaram no teste implementado pela função fornecida.
});

console.log(filteredUsers);
Check if video is stopped or playing Javascript only
var video = document.getElementsByTagName("video");
if (video[0].paused) {
    console.log("video is stopped");
    //DO SOMETING...
} else {
    console.log("video is playing");
    //DO SOMETHING...
}

//OR YOU CAN GET video DOM OBJ USING ID
var video = document.getElementById("videoId");
if (video.paused) {
    console.log("video is stopped");
    //DO SOMETING...
} else {
    console.log("video is playing");
    //DO SOMETHING...
}
Videojs check if video is playing
var videoObj = videojs("video_id");

if (!videoObj.paused()) {
    console.log("Video is playing");
} else {
    console.log("Video is paused");
}

//USING .paused() function of videojs
Get first 10 words from string javascript
function getWordStr(str) {
    return str.split(/\s+/).slice(0, 10).join(" ");
}

//TO CALL THIS FUNCTION
var fullStr = "We can get first 10 words form this string using the above function";
var finalStr = getWordStr(fullStr);

console.log(finalStr);
xhr post request with form data javascript
var data = new FormData();
data.append('username', 'username');
data.append('email', 'email');

var xhr = new XMLHttpRequest();
xhr.open('POST', 'api_url', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // YOU WILL FIND RESPONSE HERE
    console.log(this.responseText);
};
xhr.send(data);
Remove last character of a string in Javascript
var str = "Hello World";
var finalStr = str.substring(0, str.length-1);
Testest
dsds
test
test
Generate Unique ID
const uuid = (lenght = 10) =>{
    const charts = "abcdefghijklmnopqrstuvwzywABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    let id = "";
    
    for(let i = 0 ; i < lenght;i++){
        id += charts[Math.floor(Math.random() * charts.length)];
    }
    return id;
}
Password Checker
let passwordChecker = (password) => {
	if (isUpperCase(password) && isLowerCase(password) && isNumber(password) && isProperLength(password) && consOcc(password)){
		return true
	} else {
		return false
	}
}

let consOcc = (password) => {
	let init = password.charAt(0)
	let count = 1
	for (let i=1; i < password.length; i++) {
		if (password.charAt(i) == init) {
			init = password.charAt(i)
			count++
			if (count > 2) {
				return false
			}
		} else {
			init = password.charAt(i)
			count = 1 
		}
	}
	if (count>=3) {
		return false	
	}
	else {
		return true
	}
	// 
}

let isUpperCase = (password) => {
	return /[A-Z]/.test(password)
}

let isLowerCase = (password) => {
	return /[a-z]/.test(password)
}

let isNumber = (password) => {
	return /[0-9]/.test(password)
}

let isProperLength = (password) => {
	if (password.length >= 6 && password.length <= 16) {
		return true;
	}
	return false
}
Promise Chaining
new Promise(function (resolve, reject) {
    setTimeout(() => resolve(1), 1000); // (*)
}).then(function (result) { // (**)
    alert(result); // 1
    return result * 2;
}).then(function (result) { // (***)
    alert(result); // 2
    return result * 2;
}).then(function (result) {
    alert(result); // 4
    return result * 2;
});
Get all child elements of parent element in javascript
var parent = document.getElementById("parent_id");
var childrens = parent.children;
//RETURNS ALL CHILD ELEMENTS HTMLCollection ARRAY
Add new item at first position of array using unshift() method Javascript
var items = ["Apple", "Banana", "Orange"];
items.unshift("Papaya", "Watermelon");
console.log(items);
MAthPix equation
function checkIfEquationExists(str){
    str2 = str.replace(/\["|]/g," ")
    str3 = str2.replace(/[,[]/g," ")
    str4 = str3.replace(/"/g ," ")
    return str4;
}
Loop through object javascript
var items = {
    "item_1": "1",
    "item_2": "2",
    "item_3": "3"
}
for (var item in items) {
    console.log(items[item]);
}
Javascript getAbsolutePath
//Javascript get current url 
function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
Aerofiler Snippets Javascript
// Aerofiler Search Results Selector 1st column
.ag-header-viewport  .ag-header-container  .ag-header-row:nth-child(1)  .ag-header-cell:nth-child(1)  span.ag-header-cell-text
// Aerofiler Dashboard page - doc activity area- click 1st doc link
document.querySelector("#actTable tbody tr:nth-child(1) a").click()
// Locate and  button using attribute value
document.querySelector("button[data-target='#relatedDocsModal']").click()
document.querySelector("button[data-target='#relatedDocsModal'][data-toggle='modal']").click()
//Search page - get number of doc titles in search results
document.querySelectorAll("div[col-id=title] .wrap").length

//////////////////
//for(count=1;count<=5;count++)
{
  // console.log(document.querySelectorAll("div[role='gridcell'][col-id='startDate']")[count].textContent);
//document.querySelectorAll("div[role='gridcell'][col-id='startDate']")[count].textContent;
}
 // document.querySelectorAll("div[col-id=title] .wrap")[count].innerText;
   //document.querySelectorAll("div[col-id='title'] .wrap")[count].textContent;
//document.querySelectorAll("div[role='gridcell'][col-id='startDate']").textContent

var titles=document.querySelectorAll("div[role='gridcell'][col-id='startDate']");

console.log(titles[1].textContent);
npm module creation/publish
// --  npm module creation
let npmjsAuthCredentials = {
    username : 'purplecrow',
    password : '7600Akshat397973'
}

// -- login using cli

// npm folder  with same name as 
// that in the package & .js file in the package

// npm add user - if needed there for authenticating the 
// user to publish the credentials

// npm version if u want to add new one 
// npm publish
// Note:- Errors - before publishing git tree should be clean
// as without it , the files would not publish.

// -------   -----  for updating the version in the package to be used
//  npm install [email protected] --save


let links = [
'https://stackoverflow.com/questions/15056377/how-do-i-update-an-npm-module-that-i-published#targetText=4%20Answers&targetText=Change%20the%20version%20in%20your,version%20in%20the%20NPM%20repository'
];
Add service worker to your website
//CREATE SERVICE WORKER FILE ON ROOT NAMED AS service-worker.js(Name does not matter)
var cacheName = 'my-web-cache';
var filestoCache = [
    '/css/style.css',
    '/css/main.css',
    '/js/main.js',
    '/images/logo.png'
];

self.addEventListener('install', function(event) {
    event.waitUntil(
      caches.open(cacheName)
        .then(function(cache) {
          console.log('Opened cache');
          return cache.addAll(filestoCache);
        })
    );
});


//CALL SERVICE WORKER FILE AND INSTALL IT(GENERALLY FORM inde.html or other pages)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}
Query selectors in Javascript
//TO SELECT THE VERY FIRST ELEMENT
var element = document.querySelector(".element_class");
//YOU CAN ALSO PASS CHILD HIERARCHY INTO IT
var child_element = document.querySelector(".element_class .child_class");

//TO SELECT ALL ELEMENTS BY CLASS YOU CAN USE BELOW QUERY SELECTOR
var all_elements = document.querySelectorAll(".element_class");

//YOU CAN SLECT ELLEMENTS BY ITS CLASS NAMEs, OR IDs, or BY USING ELEMENTS NAMES LIKE
var all_divs_opn_webpage = document.querySelectorAll("div");
document.addEventListener javascript
document.addEventListener("click", function(){
    console.log("I am clicked")
});

//OR ADD EVENT ON A PARTICULAR EVENT
var button = document.getElementById("button");
button.addEventListener("click", function() {
    console.log("I am clicked on a button");
});
Basic server configuration in Nodejs
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3500;



const server = http.createServer(app);

server.listen(port);
CORS Headers in Nodejs
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Origin','*');
    res.header(
        'Access-Control-Allow-Header',
        'Origin,X-Resquested-With,Content-Type,Accept,Authorization'
        );
    if(req.method === 'OPTIONS'){
        res.header(
            'Access-Control-Allow-Methods',
            'GET,POST,PUT,PATCH,DELETE'
            );
        return res.status(200).json({});
    }
    next();
});
indexOf and lastIndexOf a string in javascript
var str = "Check where grapes found";
str.indexOf("grapes"); //It will return 12 as the index

var str = "grapes are not grapes until found";
str.lastIndexOf("grapes"); // Return last index of 'grapes' in str var
JavascriptFirst
var str = "Welcome Developer";
console.log(str);
Get Pseudo elements using Javascript
var elem = window.getComputedStyle(document.querySelector('.element'), ':before');
elem.getPropertyValue('color');
Create random string in Javascript
const result = Math.random().toString(36).substring(2, 15);

console.log(result);
Add class to an element in javascript
var element = document.getElementById("element_id");
element.classList.add("className"); // ADD CLASS TO ELEMENT

element.classList.remove("className"); //REMOVE CLASS FROM ELEMENT
Create form data in Javascript
var form = document.getElementsByTagName("form")[0];
var formData = new FormData(form);

formData.get("title"); //TO GET A KEY(KEY NAME WILL BE name attribute defined in your input controls)
formData.set("title", "This is new title"); //TO SET NEW VALUE TO A KEY

formData.delete("about"); //TO DELETE A KEY FROM FORM DATA
Sort array using Array.sort() in javascript
//SORT ARRAY ALPHABETICALLY
var arr = ["Joe", "Victor", "Henna"];
arr.sort();
arr.reverse(); //DESCENDING ORDER

//SORT ARRAY NUMERICALLY
var numeric_arr = [50, 20, 40, 60, 10, 30];
numeric_arr.sort(function(a, b) { return a - b }); //ASCENDING ORDER
numeric_arr.sort(function(a, b) { return b - a }); //DESCENDING ORDER

//Array of Objects
var fruits = [
    { 'name': 'banana', 'color': 'yellow' },
    { 'name': 'apple', 'color': 'red' },
    { 'name': 'orange', 'color': 'orange' }
];
//SORT ARRAY OF OBJECT
fruits.sort(function (a, b) { return a.name.localeCompare(b.name) });
console.log(fruits);
Replace characters globally Javascript
var str = "Color is Green and green is a cold color";
var result = str.replace(/green/gi, "blue");

console.log(result)

// -> Color is blue and blue is a cold color
Random & Unique CSS Gradient-Color Generator
// HTML CODE
// <h1>Welcome to the game!</h1>
//   <input type="text" name="number" id="" onkeyup="generate(this)"
//      placeholder="Enter your favourite number and then press TAB">
// <div id="result">

let generate = (ele) => {
    if (!isNaN(ele.value)) {
        document.getElementById("result").innerHTML = "";
        // alert(ele.value);
        let letters = "0123456789ABCDEF";
        array_1 = [];
        array_2 = [];
        for (i = 0; i < ele.value; i++) {
            let color_1 = '#';
            let color_2 = '#';
            do {
                for (let i = 0; i < 6; i++) {
                    color_1 += letters[(Math.floor(Math.random() * 16))];
                    color_2 += letters[(Math.floor(Math.random() * 16))];
                }
                array_1.push(color_1);
                array_2.push(color_2);
            } while (!array_1.includes(color_1) && array_2.includes(color_2));
            let div = document.createElement("div");
            div.style.width = "200px";
            div.style.height = "200px";
            div.style.backgroundImage = "linear-gradient(to right," + color_1 + "," + color_2 + ")";
            div.style.color = "white";
            div.style.display = "inline-flex";
            div.style.margin = "25px";
            document.getElementById("result").appendChild(div);
        }
        array_1 = [];
        array_2 = [];
    } else {
        alert("Only Number is allowed");
        document.getElementById("result").innerHTML = "";
    }
}
Super awesome snipper
import patientReducer from '../reducers/patientReducer';
 import joinMultipleApiResponse from '../utils/joinMultipleApiResponse';
 
-const initialState = {};
Array.forEach() in javascript
const myarray = ['1', '2', '3'];

myarray.forEach((item, index) => {
    console.log("item is : " + item + ", index is : " + index);
});
Convert all characters to lowercase using toLowerCase() method in javascript
var str = "World Is Beautiful";
console.log(str.toLowerCase());