Snippets

Short and sweet re-usable source code
Q:
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'
};

Example


const data = ['one', 'two', 'four', 'three'];
shiftAndInsert(data, 3, 2);
console.log(data);
// output: ['one', 'two', 'three', 'four']
on January 8, 2022 🔥 1301 views
Q:
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 "earth.level.one".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) =>
  selectors.map(s =>
  s.replace(/\[([^\[\]]*)\]/g, '.$1.')
    .split('.')
    .filter(t => t !== '')
    .reduce((prev, cur) => prev && prev[cur], _obj)
);

Example


get(obj, 'earth.level.one', 'vibrations[0]', 'vibrations[2].range');
// ['soft mud and rocks', 1, 'medium']
on September 7, 2021 🔥 975 views
Q:
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 Array.prototype.map() 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 =>
  str
  .split(';')
  .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`
parseCookie(document.cookie);
//console: { pkg: 'math', equation: 'E=mc^2' }
on September 6, 2021 🔥 35984 views
Q:
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 🔥 1297 views
Q:
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 🔥 2001 views
Q:
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) {
  arr.push(100);
  // then execute the callback function that was passed
  callback();
}

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

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