/ Gists / ES 6

Gists - ES 6

On gists

Dynamic imports

JavaScript ES 6

examples.md #

Výhody dynamických importů v JavaScriptu

Výhody dynamických importů

  1. Code splitting (rozdělení kódu)

Místo načtení celé aplikace najednou můžeš načítat moduly až když jsou potřeba:

// Běžný statický import
import { heavyFunction } from './heavyModule.js';

// Dynamický import - načte se jen když je potřeba
button.addEventListener('click', async () => {
  const { heavyFunction } = await import('./heavyModule.js');
  heavyFunction();
});
  1. Podmíněné načítání

Můžeš načítat moduly jen za určitých podmínek:

async function loadFeature(featureName) {
  if (featureName === 'chart') {
    const { createChart } = await import('./chartModule.js');
    createChart();
  } else if (featureName === 'table') {
    const { createTable } = await import('./tableModule.js');
    createTable();
  }
}
  1. Lazy loading (líné načítání) komponent v Nuxt/Vue
// Místo tohoto statického importu
import HeavyComponent from '@/components/HeavyComponent.vue';

// Můžeš použít dynamický import
const HeavyComponent = defineAsyncComponent(() => 
  import('@/components/HeavyComponent.vue')
);
  1. Lepší výkon první načtení stránky

Zmenšíš hlavní bundle a zrychlíš tak první vykreslení:

// V Nuxt 3 můžeš dynamicky importovat i stránky
const routes = [
  {
    path: '/',
    component: () => import('./Home.vue')
  },
  {
    path: '/dashboard',
    component: () => import('./Dashboard.vue') // Načte se až při navigaci
  }
]
  1. Práce s různými formáty souborů
async function loadConfigBasedOnEnvironment() {
  if (process.env.NODE_ENV === 'development') {
    return import('./config.dev.json');
  } else {
    return import('./config.prod.json');
  }
}
  1. Lepší cachování v prohlížeči

Když změníš jeden modul, prohlížeč může znovu stáhnout jen tento modul, ne celý bundle.

  1. Vyhnutí se problémům s cyklickými závislostmi

Dynamické importy mohou někdy pomoct vyřešit cyklické závislosti:

// moduleA.js
export function funcA() {
  console.log('Function A');
}

export async function funcThatUsesB() {
  const moduleB = await import('./moduleB.js');
  moduleB.funcB();
}

// moduleB.js
import { funcA } from './moduleA.js';

export function funcB() {
  console.log('Function B calls:');
  funcA();
}

On gists

Sum column - zylacup sankce

JavaScript ES 6

sum.js #

// MUJ :D
Array.from(document.querySelector('.default').querySelectorAll('tr')).reduce((acc, tr) => {
    let num = parseInt(tr.children[5].textContent)
    if (!isNaN(num)) {
        return acc + num
    }
    return acc
}, 0)

// GPT
const total = [...document.querySelectorAll('.default tr')]
  .map(tr => parseInt(tr.children[5].textContent))
  .filter(num => !isNaN(num))
  .reduce((acc, num) => acc + num, 0);
  

// Variants 
let total = 0;
document.querySelectorAll('.default tr').forEach(tr => {
    let num = parseInt(tr.children[5].textContent);
    if (!isNaN(num)) {
        total += num;
    }
});



const total = [...document.querySelectorAll('.default tr')].reduce((acc, tr) => {
    const num = parseInt(tr.children[5].textContent);
    return !isNaN(num) ? acc + num : acc;
}, 0);



const total = [...document.querySelectorAll('.default tr')].reduce((acc, tr) =>
    acc + (parseInt(tr.children[5].textContent) || 0), 0);
    
    
    
const total = [...document.querySelectorAll('.default tr')].reduceRight((acc, tr) => {
    const num = parseInt(tr.children[5].textContent);
    return !isNaN(num) ? acc + num : acc;
}, 0);

On gists

array reduce - advanced use

JavaScript ES 6

array-reduce.js #

/*
  Resources:
  - https://javascript.plainenglish.io/10-reduce-techniques-worth-mastering-97dd9b9a9e90
  - https://andepaulj.medium.com/javascript-reduce-79aab078da23
  - https://javascript.plainenglish.io/5-use-cases-for-reduce-in-javascript-61ed243b8fef
  - https://code.tutsplus.com/5-real-life-uses-for-the-javascript-reduce-method--cms-39096a
*/

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const count = fruits.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
  return accumulator;
}, {});
console.log(count); // Output: { apple: 3, banana: 2, orange: 1 }


/* Counting Occurrences */
const fruits = [ 'Banana', 'Orange', 'Apple', 'Orange', 'Pear', 'Banana']
const occurrences = fruits.reduce((acc, currFruit) => {
    return {...acc, [currFruit]: (acc[currFruit] || 0) + 1 }
}, {})
console.log(occurrences)
/* 
{ 
Apple: 1, 
Banana: 2, 
Orange: 2, 
Pear: 1 
} 
*/

// OR
const reduceOccurrences = manyNumbers.reduce((acc, cur) => {
  acc[cur] ? acc[cur]++ : acc[cur] = 1
  return acc
}, {})

// OR via Map()
const count = (array) =>
    array.reduce(
        (acc, it) => (acc.set(it, (acc.get(it) || 0) + 1), acc),
        new Map()
    );
const array = [1, 2, 1, 2, -1, 0, "0", 10, "10"];
console.log(count(array));




/* Flatten a List of Arrays */
const arrOfArrs = [
    ['aaron', 'ake', 'anna', 'aje'],
    ['becky', 'ben', 'bright'],
    ['cara', 'chris'],
    ['david', 'daniel', 'danielle', 'djenue'],
]
const flattened = arrOfArrs.reduce((acc, array) => acc.concat(array))
console.log(flattened)
// ["aaron", "ake", "anna", "aje", "becky", "ben", "bright", "cara", "chris", "david", "daniel", // "danielle", "djenue"]

// OR
const array = [1, [2, [3, [4, [5]]]]];
const flat = (arrayNumbers) =>
    arrayNumbers.reduce(
        (acc, it) => acc.concat(Array.isArray(it) ? flat(it) : it),
        []
    );
const flatArray = flat(array);
console.log(flatArray); // [ 1, 2, 3, 4, 5 ]



/* Getting Max and Min Values */
const students = [
    { name: "Kingsley", score: 70 },
    { name: "Jack", score: 80 },
    { name: "Joe", score: 63 },
    { name: "Beth", score: 75 },
    { name: "Kareem", score: 59 },
    { name: "Sarah", score: 93 }
]
const max = students.reduce((acc, student) => {
    if(acc === null || student.score > acc) 
        return student.score
    return acc
}, null)
console.log(max) // Prints 93

// OR
const getMax = (array) => array.reduce((max, num) => (max > num ? max : num));
const getMin = (array) => array.reduce((max, num) => (max < num ? max : num));



/* Converting Between Types */ 
const studentsArray = [
    { name: "Kingsley", score: 70, position: "1st" },
    { name: "Jack", score: 80, position: "2nd" },
    { name: "Joe", score: 63, position: "3rd" },
    { name: "Beth", score: 75, position: "4rd" },
    { name: "Kareem", score: 59, position: "5th" },
    { name: "Sarah", score: 93, position: "6th" }
]
const studentObj = studentsArray.reduce((acc, student) => {
	return {...acc, [student.name]: student.position}
}, {})
console.log(studentObj)
/* 
{ 
Beth: "4rd", 
Jack: "2nd", 
Joe: "3rd", 
Kareem: "5th", 
Kingsley: "1st", 
Sarah: "6th" 
} 
*/



/* Grouping objects by a property */
const result = [
    {subject: 'Physics', marks: 41},
    {subject: 'Chemistry', marks: 59},
    {subject: 'Pure Maths', marks: 36},
    {subject: 'Applied Maths', marks: 90},
    {subject: 'English', marks: 64},
];

let initialValue = {
    pass: [], 
    fail: []
}

const groupedResult = result.reduce((accumulator, current) => {
    (current.marks>=50) ? accumulator.pass.push(current) : accumulator.fail.push(current);
    return accumulator;
}, initialValue);

console.log(groupedResult);
/*
{
 pass: [
  { subject: ‘Chemistry’, marks: 59 },
  { subject: ‘Applied Maths’, marks: 90 },
  { subject: ‘English’, marks: 64 }
 ],
 fail: [
  { subject: ‘Physics’, marks: 41 },
  { subject: ‘Pure Maths’, marks: 36 }
 ]
}
*/




/* Reduce is a Higher-Order Function*/
const plusTwoReducer = (acc, cur) => {
  acc.push(cur + 2)
  return acc
}

const plusSixReducer = (acc, cur) => {
  acc.push(cur + 6)
  return acc
}

numbers.reduce(plusTwoReducer, [])
numbers.reduce(plusSixReducer, [])





On gists

Converting an Array of Objects to an Object

JavaScript ES 6

convert.js #

// https://medium.com/@Evelyn.Taylor/rewriting-javascript-converting-an-array-of-objects-to-an-object-7aeaed399017

const people = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

=>

{
  1: 'Alice',
  2: 'Bob',
  3: 'Charlie'
}


// traditional
const peopleObject = {};

for (const person of people) {
  peopleObject[person.id] = person.name;
}

console.log(peopleObject); // {1: 'Alice', 2: 'Bob', 3: 'Charlie'}



// better
const peopleObject = people.reduce((acc, person) => {
  acc[person.id] = person.name;
  return acc;
}, {});

console.log(peopleObject); // {1: 'Alice', 2: 'Bob', 3: 'Charlie'}



// maybe better, maybe less readable, shorter
const peopleObject = people.reduce((acc, { id, name }) => ({ ...acc, [id]: name }), {});

On gists

Destructuring & default values

JavaScript ES 6

destructuring-default-values.js #

const { data } = await axios.get(...)
const { data: newData } = await axios.get(...)




const { id = 5 } = {}
console.log(id) // 5




function calculate({operands = [1, 2], type = 'addition'} = {}) {
    return operands.reduce((acc, val) => {
        switch(type) {
            case 'addition':
                return acc + val
            case 'subtraction':
                return acc - val
            case 'multiplication':
                return acc * val
            case 'division':
                return acc / val
        }
    }, ['addition', 'subtraction'].includes(type) ? 0 : 1)
}

console.log(calculate()) // 3
console.log(calculate({type: 'division'})) // 0.5
console.log(calculate({operands: [2, 3, 4], type: 'multiplication'})) // 24

On gists

Memoization (cache for eg)

JavaScript ES 6

memoize-caching.js #

function memoize(fn) 
{
    // Create an object to store cached results.
    const cachedResult = {};

    // Return an anonymous function.
    return function() 
    {
        // Generate a unique key based on the function arguments.
        var key = JSON.stringify(arguments);

        // Check if the result for the current arguments is not cached.
        if (!cachedResult[key]) 
        {
            /*
                If not cached, compute the result by calling the 
                product function with the arguments.
            */
            cachedResult[key] = fn(...arguments);
        }
        // Return the cached result.
        return cachedResult[key];
    }
}


const product=(num1, num2)=>
{
    // Intentionally running the costly loop
    for(let i=0;i<10000000;i++){}

    // Returning the product
    return num1*num2;
}

const memoizedProduct=memoize(product)

console.time("1st Call")
console.log(memoizedProduct(22222,12345))
console.timeEnd("1st Call")

console.time("2nd Call")
console.log(memoizedProduct(22222,12345))
console.timeEnd("2nd Call")



//Output of 1st call
274330590
1st Call: 20.973ms

//Output of 2nd call
274330590
2nd Call: 0.278m

On gists

7 ways - Remove Duplicates Array of objects

JavaScript ES 6

duplicates.js #

// 0
const obj = [{ id: 1 }, { id: 2 }, { id: 3 }];

obj.forEach((o, i) => {
    if (o.id == 2) {
        obj.splice(o, 1);
    }
});

console.log(obj);




    const arr = [
        { id: 1, name: 'Tom' },
        { id: 1, name: 'Tom' },
        { id: 2, name: 'Nick' },
        { id: 2, name: 'Nick' },
    ];

// 1#

const ids = arr.map(({ id }) => id);
const unique = arr.filter(({ id }, index) =>
    !ids.includes(id, index + 1));


// 2#

const unique = arr.filter((obj, index, selfArr) => {
    return index === arr.findIndex(o => obj.id === o.id); // arr === selfArr
});


 
	https://bobbyhadz.com/blog/javascript-remove-duplicates-from-array-of-objects 


// 3#

const uniqueIds = [];
const unique = arr.filter(element => {
    const isDuplicate = uniqueIds.includes(element.id);

    if (!isDuplicate) {
        uniqueIds.push(element.id);
        return true;
    }
    return false;
});

//  [{id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}]



// ✅ If you need to check for uniqueness based on multiple properties
const arr2 = [
    { id: 1, name: 'Tom' },
    { id: 1, name: 'Tom' },
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Nick' },
    { id: 2, name: 'Nick' },
    { id: 2, name: 'Bob' },
];
const unique2 = arr2.filter((obj, index) => {
    return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});

// [
//   { id: 1, name: 'Tom' },
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Nick' },
//   { id: 2, name: 'Bob' }
// ]
console.log(unique2);


// #4 same as 3# but with Set

const uniqueIds = new Set()
const unique = arr.filter(element => {
	const isDuplicate = uniqueIds.has(element.id);
	uniqueIds.add(element.id);;

    if (!isDuplicate) {
        return true;
    }
    return false;
});


// #5 same as #1

const unique = arr.filter((obj, index) => {
  return index === arr.findIndex(o => obj.id === o.id);
});


// #6 same as #5 but with multiple props

const unique2 = arr2.filter((obj, index) => {
  return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});


// last duplicate objects

const unique = arr.filter((obj, index) => {
  return index === arr.findLastIndex(o => obj.id === o.id);
});


// Map solution
    const arr = [
        { id: 1, name: 'Tom' },
        { id: 1, name: 'Tom' },
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Nick' },
        { id: 2, name: 'James' },
    ];

    function removeDuplicateObjects(arr, property) {
        return [...new Map(arr.map(obj => [obj[property], obj])).values()];
    }

// [ { id: 1, name: 'Alice' }, { id: 2, name: 'James' } ]
    console.log(removeDuplicateObjects(arr, 'id'));
    
    /* Same */
    const persons= [
      { id: 1, name: 'John',phone:'23' },
      { id: 2, name: 'Jane',phone:'23'},
      { id: 1, name: 'Johnny',phone:'56' },
      { id: 4, name: 'Alice',phone:'67' },
    ];
    const unique = [...new Map(persons.map((m) => [m.id, m])).values()];
    

// [
//   { id: 1, name: 'Tom' },
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Nick' },
//   { id: 2, name: 'James' }
// ]
    console.log(removeDuplicateObjects(arr, 'name'));

    console.log(unique);

On gists

5 ways - unique values in array

JavaScript ES 6

unique-values-in-array.js #

const arr = [
	'banan',
	'apple',
	'orange',
	'lemon',
	'apple',
	'lemon',
]

// 1 no duplicities filter
function removeDuplicities(data) {
	return 	data.filter((value, index) => data.indexOf(value) === index)
}

// 1 only duplicities filter
function onlyDuplicities(data) {
	return 	data.filter((value, index) => data.indexOf(value) !== index)
}


// 2 set
[...new Set(arr)]



// 3 forEeach
let unique = []
arr.forEach(item => {
	if (!unique.includes(item)) {
		unique.push(item)
	}
})



// 4 reduce #1
let unique = arr.reduce((acc, curr) => {
	if (acc.indexOf(curr) < 0) {
		acc.push(curr)
	}
	return acc
}, [])



// 4 reduce #2
let unique = arr.reduce((acc, curr) => {
	return acc.includes(curr) ? acc : [...acc, curr]
}, [])


// 5  prototype #1
Array.prototype.unique = function() {
	let unique = []

	this.forEach((item) => {
	  if (!unique.includes(item)) {
		unique.push(item)
	  }	
	})
	return unique
}


// 5  prototype #2
Array.prototype.unique = function() {
	return [...(new Set(this))] // or Array.from() instead of [...]
}


On gists

Vyhozeni duplicitnich objektu v poli objektu

JavaScript ES 6

array-object-unique.js #

let x = [
	{
		id: 1,
		name: 'A'
	},
	{
		id: 2,
		name: 'B'
	},
	{
		id: 3,
		name: 'C'
	},
	{
		id: 3,
		name: 'C'
	},
	{
		id: 2,
		name: 'B'
	},
]



// 1
let uniqueArray = [];
let idMap = {};

for (let obj of x) {
	if (!idMap[obj.id]) {
		idMap[obj.id] = true;
		uniqueArray.push(obj);
	}
}



// 2
let uniqueArray = x.filter((obj, index, self) => 
    index === self.findIndex((o) => o.id === obj.id)
);



// 3
let uniqueArray = x.reduce((accumulator, currentValue) => {
    if (!accumulator.some(obj => obj.id === currentValue.id)) {
        accumulator.push(currentValue);
    }
    return accumulator;
}, []);



console.log(uniqueArray)

On gists

JavaScript Union, Intersection, and Difference With ES6 Set

JavaScript ES 6

demo.js #

/* 
https://medium.com/just-javascript-tutorials/javascript-union-intersection-and-difference-with-es6-set-13b953b21f62
*/

const setA = new Set(['🌞', '🌝', '🌎']);
const setB = new Set(['🌎', '🚀', '👩‍🚀']);

const union = new Set([...setA, ...setB]);
console.log(union); // Set(5) { '🌞', '🌝', '🌎', '🚀', '👩‍🚀' }

const intersection = new Set([...setA].filter((x) => setB.has(x)));
console.log(intersection); // Set(1) { '🌎' }

const difference = new Set([...setA].filter((x) => !setB.has(x)));
console.log(difference); // Set(2) { '🌞', '🌝' }