Skip to content

Instantly share code, notes, and snippets.

View munkacsitomi's full-sized avatar

Tamás Munkácsi munkacsitomi

  • Amsterdam, Netherlands
View GitHub Profile
@munkacsitomi
munkacsitomi / map-types.js
Last active February 3, 2022 10:36
Map types
const stringNumbers = ['123', '4.45', '5,25', 'abc', '10000'];
const numbers = stringNumbers.map(Number);
console.log(numbers); // [123, 4.45, NaN, NaN, 10000]
const stringBoolean = ['false', false, '0', 0, null, undefined];
const booleans = stringBoolean.map(Boolean);
console.log(booleans); // [true, false, true, false, false, false]
@munkacsitomi
munkacsitomi / multiple-error-handling.js
Last active February 2, 2022 12:34
Multiple error handling
async send() {
let success = false;
try {
const { data } = await httpPost();
success = !data?.errors || data.errors.length === 0;
} catch(e) {
// handled below because failure can happen on two occasions
// 1. httpPost fails
// 2. the call was successful but the BE gives back error
throw e;
@munkacsitomi
munkacsitomi / array-utils.js
Last active February 3, 2022 10:37
Array utilities
// Compares 2 arrays of (primitive) values to see if they are the same
const doArraysMatch = (arr1, arr2) => arr1.length === arr2.length && arr1.every((element) => arr2.includes(element));
// Reusable function to combine arrays
const mergeArr = (...arr) => arr.reduce((acc, val) => [...acc, ...val], []);
// Group an array of objects by a specific key or property value
const movies = [
{ title: 'Test 1', year: 2020 },
{ title: 'Test 2', year: 2020 },
@munkacsitomi
munkacsitomi / doubleList.js
Created December 2, 2020 14:25
Fun JavaScript stuff
// Old, imperative way
const originalDoubleList = list => {
const newList = [];
for (let i = 0; i < list.length; i++) {
newList[i] = list[i] * 2;
}
return newList;
};
console.log(originalDoubleList([20]));
@munkacsitomi
munkacsitomi / cache.js
Created September 14, 2020 19:19
Caching function calculation results
function cached(fn) {
// Create an object to store the results returned after each function execution.
const cache = Object.create(null);
// Returns the wrapped function
return function cachedFn(str) {
// If the cache is not hit, the function will be executed
if (!cache[str]) {
let result = fn(str);
@munkacsitomi
munkacsitomi / getNumber.js
Last active August 26, 2020 09:29
How to swap keys and values in an Object and how to handle different types in JS
const swapKeyVal = (obj) => Object.assign({}, ...Object.entries(obj).map(([a,b]) => ({ [b]: a })));
const getNumber = (num) => {
const isStringType = typeof num === 'string';
const isNumberType = typeof num === 'number';
let hasNumber = false;
let keyVal = { one: 1, two: 2, three: 3 };
if (!isStringType && !isNumberType) {
throw new Error('Unknown type');
@munkacsitomi
munkacsitomi / git-examples.sh
Last active May 22, 2023 12:11
Useful Git commands
# get all branches
git fetch
# undo any unplanned changes
git reset --hard
# revert last commit
git reset --hard HEAD^
# reset to develop branch
git reset --hard origin/develop
# set the author name and email address to your commits
git config --global user.name "Your Name"
@munkacsitomi
munkacsitomi / duplicated.js
Created March 10, 2020 14:55
Filter duplicated values from array
const tmp = [1, 2, 3, 1, 3, 4, 5];
const uniqueFirst = Array.from(new Set(tmp));
const uniqueSecond = tmp.filter((item, index) => tmp.indexOf(item) === index);
const uniqueThird = tmp.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
const duplicatedValues = tmp.filter((item, index) => tmp.indexOf(item) !== index);
console.log(uniqueFirst);
console.log(uniqueSecond);
@munkacsitomi
munkacsitomi / no-need-to-reduce.js
Created March 10, 2020 13:24
We don't need to use reduce if it's not necessary
const ids = [100, 101, 102, 103];
// We can use reduce to wrap ids in an object
const first = ids.reduce((out, id) => {
out.push({ id });
return out;
}, []);
// Or use map to do the same
const second = ids.map((id) => {
@munkacsitomi
munkacsitomi / promise-all-error-handling.js
Created March 1, 2020 15:47
Promise.all error handling
const pause = (data, time) => new Promise(resolve => setTimeout(() => resolve(data), time));
const pauseReject = (data, time) =>
new Promise((resolve, reject) =>
setTimeout(() => reject(new Error(`Something went wrong in the ${data} promise`)), time)
);
const parallelErrorHandlingWrong = () => {
const firstPromise = pause('first', 3000);
const secondPromise = pauseReject('second', 2000);
const thirdPromise = pause('third', 1000);