/ Gists

Gists

On gists

Faster way than isset

PHP tricks - one liners PHP

isset.php #

<?php

/*
  if (isset($a['b'])) {
    $x = $a['b'];
    echo $x;
  }

*/

if ($x = ($a['b'] ?? null)) {
    echo $x;
}

On gists

Better prev/next index in array

JavaScript Vue.js

app.js #

// after our data inside the Vue instance
  computed: {
    currentImage () {
      return images[this.currentImageIndex]
    },
    previousImageIndex () {
      return (this.currentImageIndex - 1 + images.length) % images.length
    },
    previousImage () {
      return images[this.previousImageIndex]
    },
    nextImageIndex () {
      return (this.currentImageIndex+1) % images.length
    },
    nextImage () {
      return images[this.nextImageIndex]
    },
  }

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

Parent - Child (height - min-height inherited)

CSS CSS trick

app.css #

/* 1 */
.parent
{
  	min-height: 200px;
  	height: 1px;
	border: 3px solid black;
}

.child
{
  background: mistyrose;
  height: 100%;
}


/* 2 */
.parent
{
  	min-height: 200px;
	border: 3px solid black;
	display: flex;
	
}

.child
{
  background: mistyrose;
  width: 100%;
}


/* 3 */
.parent
{
  	min-height: 200px;
	border: 3px solid black;
	display: flex;
	flex-direction: column;
	
}

.child
{
  background: mistyrose;
  flex: 1;
}


/* 4 */
.parent
{
  min-height: 200px;
	border: 3px solid black;
	display: grid;
}

.child
{
  background: mistyrose;
}


/* 5 */
.parent
{
  	min-height: 200px;
	border: 3px solid black;
	
	
}

.child
{
  background: mistyrose;
	min-height: inherit;
}

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

Css scrollable centered modal

CSS CSS trick

style.css #

/* to the body element */
.noscroll { 
	overflow: hidden; 
}

.overlay { 
   	position: fixed; 
   	overflow-y: scroll;
   	inset: 0;
	place-items: center;

}

[aria-hidden="true"] { display: none; }
[aria-hidden="false"] { display: grid; }




/* this code is not strictly necessary: just to make this demo a bit pleasant */

.overlay div {
   width: 80%;
   max-width: 650px;
   padding: 30px;
   background: rgba(255,255,255, .95);
}

.overlay {
    background:  rgba(40,40,40, .75);
}




* { box-sizing: border-box; }
button { padding: 1.5em 4em; cursor: pointer;}
pre { background: #fafafa; padding: 15px; border: 1px #ccd dashed; }
pre + p { margin: 5vh 0; }

On gists

Flexbox Solver

CSS CSS trick

solver.css #

/*

https://kentondejong.medium.com/this-css-1-liner-will-improve-your-flexbox-7e40e977ef5c

*/

.parent {
  --gap: 20px;
  --columns: 5;
  display: flex;
  gap: var(--gap);
  flex-wrap: wrap;
		
}

.child {
	
flex: 0 1 calc((100% / var(--columns)) - var(--gap) + (var(--gap) / var(--columns)));
	
}