A code snippet is a short piece of code that is used to perform a specific task. They are a great way to save time, like mini-programs that can be printed out, copied onto another document, or saved as a file for future use!

For Terminal Commands instead (CLI), read this post.

Javascript

Shift items of an array by n indexes

We need to use the pop and unshift functions. Note that pop returns the popped value, which can be used later inside unshift.

const arr = [1, 2, 3];
let n = 2;

for(let i = 0; i < n; i++) {
	let poppedVal = arr.pop();
	arr.unshift(poppedVal);
};

console.log(arr);

[2, 3, 1]

Convert an array into an object

Here we face an quite advance use case of the reduce function.

const arr = [1, 2, 3];

const obj = arr.reduce((acc, curr, i) => {
	acc['index'+i] = curr;
	return acc;
}, {});

console.log(obj);

{index0: 1, index1: 2, index2: 3}

Check if 2 objects are equal

In JavaScript, we cannot directly compare two objects by equality operators (== or ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data (those are two different object instances so they are referring to two different objects).

const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
const obj3 = { a: 1, c: 3 };

const areEqual = function (obj1, obj2) {
  // if both objects have the same number of keys (properties)
  if (Object.keys(obj1).length === Object.keys(obj2).length) {
    // if every key of obj1 matches with the corresponding key of obj2 and values of the same keys of both objects match
    return Object.keys(obj1).every(
      (key) => obj2.hasOwnProperty(key) && obj2[key] === obj1[key]
    );
  }
  return false;
};

console.log(areEqual(obj1, obj2));
console.log(areEqual(obj1, obj3));

true
false

Get number of same occurences in a list

I've been asked this question during a live coding interview.

const phoneNumbers = [
	"+33656231243",
	"+33627635461",
	"+33742536788",
	"+33742536788",
	"+33627635461",
	"+33656231243",
	"+33452678901",
	"+33656231243",
	"+33742536788",
];

const times = phoneNumbers.reduce((acc, curr) => {
	acc[curr] ? acc[curr]++ : (acc[curr] = 1);
	return acc;
}, {});

console.log(times);

{
   '+33656231243': 3,
   '+33627635461': 2,
   '+33742536788': 3,
   '+33452678901': 1
}

Check if a list contains duplicate values

const list = [3, 2, 1, 2, 4, 1, 2];

let singleValues = Array(Math.max(...list) - Math.min(...list) + 2).fill(0);
for (val of list) singleValues[val]++;

// Get list of duplicates
const duplicates = singleValues
  .map((val, i) => (val > 1 ? i : null))
  .filter((val) => val !== null);

// Get the value that appears the most
const mostFrequent = singleValues.indexOf(Math.max(...singleValues));

console.log("duplicates:", duplicates);
console.log("mostFrequent:", mostFrequent);

duplicates: [ 1, 2 ]
mostFrequent: 2

Remove duplicates from a list

const list = [1, 2, 1, 2, 5, 3, 4, 5];

// Solution 1: using Set()
const uniqueSet = (arr) => [...new Set(arr)];

// Solution 2: creating a new array
const uniqueArray = (arr) => {
  const uniqueValues = [];
  list.forEach((val) => {
    if (!uniqueValues.includes(val)) uniqueValues.push(val);
  });
  return uniqueValues;
};

console.log(uniqueSet(list));
console.log(uniqueArray(list));

[1, 2, 5, 3, 4]
[1, 2, 5, 3, 4]

Get rows, columns and diagonals of a matrix

const MATRIX = [
  [4, 9, 2],
  [3, 5, 7],
  [8, 1, 5],
];

function getRowsColsDiags(matrix) {
  const rows = [...matrix];
  const cols = [];
  const diags = [[], []];
  for (let i = 0; i < matrix.length; i++) {
    cols.push([]);
    for (let j = 0; j < matrix.length; j++) {
      cols[i].push(matrix[j][i]);
    }
    diags[0].push(matrix[i][i]);
    diags[1].push(matrix[i][matrix.length - 1 - i]);
  }
  return [rows, cols, diags];
}

const [rows, cols, diags] = getRowsColsDiags(MATRIX);
console.log(cols);
console.log(diags);

[ [ 4, 3, 8 ], [ 9, 5, 1 ], [ 2, 7, 5 ] ]
[ [ 4, 5, 5 ], [ 2, 5, 8 ] ]

Make an arrays concatenation function

// Solution 1: using spread operator
function concatArrays(...arrays) {
  return arrays.reduce((acc, curr) => [...acc, ...curr]);
}

// Solution 2: using concat()
function concatArrays(...arrays) {
  return arrays.reduce((acc, curr) => acc.concat(curr), []);
}

const singleArr = concatArrays([1, 2], [2, 3], [3, 4], [4, 5]);
console.log(singleArr);

[1, 2, 3, 4, 5]

Python

Get all Environment Variables of a project

from os import environ

for i in environ:
	print(e, ':', environ[e])
# Output

SHELL : /bin/bash
SESSION_MANAGER : local/freedom:@/tmp/.ICE-unix/4012,unix/freedom:/tmp/.ICE-unix/4012
QT_ACCESSIBILITY : 1
...

Create MySQL database

# db-create.py

import mysql.connector

host = "localhost"
user = "root"
password = "root"
dbname = "buffalerts"

db = mysql.connector.connect(host=host, user=user, password=password)
cursor = db.cursor()
cursor.execute("SHOW DATABASES")

dbExists = False
for x in cursor:
    if dbname in x:
        dbExists = True
if dbExists:
    print(f'Database "{dbname}" already exists!')
else: 
    cursor.execute(f"CREATE DATABASE {dbname}")
pip install mysql-connector-python
python3 db-create.py
⇐ Python Script automation on...Basic CRUD App with Flask and... ⇒
Image
Author of this website. I am passionate about programming and web design since the age of 12. After a stint in architecture and entrepreneurship, I came back to my original passion at 30 years old and became a self-taught web developer in less than 2 years.

Leave a Comment