/ Gists / JavaScript

Gists - JavaScript

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

Remove style from HTML

JavaScript

remove-inilne-style.js #

  sanitizedText(src) {
    const div = document.createElement('div');
    div.innerHTML = src;
    const elements = div.querySelectorAll('*');
    elements.forEach((element) => {
      element.removeAttribute('style');
    });
    return div.innerHTML;
  }

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) { '🌞', '🌝' }

On gists

Currying fn

JavaScript

curryfn.js #

// Currying function for calculating the total price
function calculateTotal(price) {
  return function(tax) {
    return function(quantity) {
      return price * quantity * (1 + tax);
    };
  };
}

// Create a curried function for a specific product
const calculateTotalForProduct = calculateTotal(10.99); // Set the base price

// Calculate the total price for a specific product with 8% tax and 3 quantity
const total = calculateTotalForProduct(0.08)(3);
console.log(`Total Price: $${total.toFixed(2)}`);

On gists

webp image javascript browser detection

JavaScript ES 6

detection.js #

// https://www.jianshu.com/p/3ab716ee1a2e

  const supportsWebp = ({ createImageBitmap, Image }) => {
      if (!createImageBitmap || !Image) return Promise.resolve(false);

      return new Promise(resolve => {
          const image = new Image();
          image.onload = () => {
              createImageBitmap(image)
                  .then(() => {
                      resolve(true);
                  })
                  .catch(() => {
                      resolve(false);
                  });
          };
          image.onerror = () => {
              resolve(false);
          };
          image.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=';
      });
  };

  const webpIsSupported = () => {
      let memo = null;
      return () => {
          if (!memo) {
              memo = supportsWebp(window);
              console.log('memo');
          }
          return memo;
      };
  };

  const result = webpIsSupported();

  result()
      .then(res => {
          alert('OK', res);
      })
      .catch(err => {
          alert(err);
      });

  result()
      .then(res => {
          alert('OK', res);
      })
      .catch(err => {
          alert(err);
      });

On gists

reveal.js

JavaScript

reveal.js #

function reveal() {
        var reveals = document.querySelectorAll(".reveal");
        for (var i = 0; i < reveals.length; i++) {
          var windowHeight = window.innerHeight;
          var elementTop = reveals[i].getBoundingClientRect().top;
          var elementVisible = 150;
          if (elementTop < windowHeight - elementVisible) {
            reveals[i].classList.add("active");
          } else {
            reveals[i].classList.remove("active");
          }
        }
      }
      window.addEventListener("scroll", reveal);