Short and sweet re-usable source code
How to place an element in an array from one place to another?

Consider the array ['one', 'two', 'four', 'three'] and we want to arrange the last two element.

 * move element one place to other in existing array
 * @param {any[]} arr: array Value
 * @param {number} from: index of value that need to be moved
 * @param {number} to: index where need to be placed
export const shiftInsert = (arr: any[], from: number, to: number) => {
  const cutOut = arr.splice(from, 1)[0]; // cut the element at index 'from'
  arr.splice(to, 0, cutOut);            // insert it at index 'to'


const data = ['one', 'two', 'four', 'three'];
shiftAndInsert(data, 3, 2);
// output: ['one', 'two', 'three', 'four']
on January 8, 2022 🔥 632 views
How to get properties indicated by given selectors from an object?

Consider an object from which we want to retrive properties.

const obj = {
  earth: { level: { one: 'soft mud and rocks' } },
  vibrations: [1, 2, { range: 'medium' }],
  • Use [...].map() for each selector, "vibrations[2].range".replace() to replace square brackets with dots.
  • Use "".split('.') to split each selector.
  • Use [...].filter() to remove empty values and [...].reduce() to get the value indicated by each selector.

const get = (_obj, selectors) => =>
  s.replace(/\[([^\[\]]*)\]/g, '.$1.')
    .filter(t => t !== '')
    .reduce((prev, cur) => prev && prev[cur], _obj)


get(obj, '', 'vibrations[0]', 'vibrations[2].range');
// ['soft mud and rocks', 1, 'medium']
on September 7, 2021 🔥 449 views
How to parse cookies in javascript?

In the browser cookies is store in string format containing key-value pairs.
So, how to parse a browser Cookie string and return an object of all cookie name-value pairs?

  • separate each key-value pair using String.prototype.split(';')
  • Use and String.prototype.split('=') to separate keys from values in each pair.
  • Use Array.prototype.reduce() and decodeURIComponent() to create an object with all key-value pairs.

const parseCookie = str =>
  .map(v => v.split('='))
  .reduce((acc, v) => {
    acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
    return acc;
  }, {});
// cookie in browser: `pkg=math; equation=E%3Dmc%5E2`
//console: { pkg: 'math', equation: 'E=mc^2' }
on September 6, 2021 🔥 13566 views
How to use for loops to break out early in javascript?

for loop in modern JavaScript is rarely talked about although it’s only useful in asynchronous operation scenarios.
But what breaking out early consider the following example:
Matching two array

const smallArray = [0, 2];
const largeArray = Array.from({ length: 1000 }, (_, i) => i);

const areEqual = (a, b) => {
  let result = true;
  a.forEach((x, i) => {
    if (!result) return;
    if (b[i] === undefined || x !== b[i]) result = false;
  return result;
areEqual(largeArray, smallArray); // false
// Will loop over all items in `largeArray`

The code isn’t optimized, but it highlights the issue of array methods, such as [].forEach() being unable to break out of the loop early.
To counteract this, we could use a for loop and an early return instead:

const areEqual = (a, b) => {
  for (let i in a) {
    if (b[i] === undefined || a[i] !== b[i]) return false;
  return true;
areEqual(largeArray, smallArray); // false
// Will only loop until the first mismatch is encountered
on September 3, 2021 🔥 626 views
How to create a cookie using JavaScript?

The simplest way to create a cookie is to assign a string value to the document.cookie object, for example-

document.cookie = "key1 = value1; key2 = value2; expires = date";
// Example
var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000); //set cookies to expire in 1 hour
document.cookie = `${key} = ${value}; ${opt} = ${opt_value}; expires = ${now.toUTCString()};`;

const cookie = document.cookie will return all cookies in one string much like:
cookie1=value; cookie2=value; cookie3=value;

on September 3, 2021 🔥 954 views
How to write a callback function in javascript?

A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed.
for example of a simple callback function that logs to the console after some operations have been completed.

function extendArray(arr, callback) {
  // then execute the callback function that was passed

var arr = [1, 2, 3, 4, 5];

extendArray(arr, function() {
  console.log("array has been modified", arr);
on September 2, 2021 🔥 704 views