/ Gists

Gists

On gists

OOP JS Class - static properties

JavaScript-OOP JavaScript

static.js #

class Item {
	
  static count = 0
  static count2 = 0
	
  constructor(name) {
    this.name = name
    this.constructor.count++
	Item.count2++
	
	console.log(this)
	console.log('-----------------------------------------')
	console.log(this.constructor)
  }

  
  static getCount() {
    return Item.count
  }

  static getCount2() {
    return Item.count2
  }
}


let A = new Item("A");
let B = new Item("B");

/*
console.log(A.getCount()) // nelze
console.log(B.getCount2()) // nelze
*/

console.log(Item.getCount()) // 2
console.log(Item.getCount2()) // 2



/*


[object Object] {
  name: "A"
}

"-----------------------------------------"

class Item {
  
static count = 0
static count2 = 0
  
constructor(name) {
  this.name = name
  this.constructor.count++
  Item.count2++
  
  window.runnerWindow.proxyConsole.log(this)
  window.runnerWindow.proxyConsole.log('-----------------------------------------')
  window.runnerWindow.proxyConsole.log(this.constructor)
}


*/

On gists

JS Mixins (Traits)

JavaScript-OOP JavaScript

Js-mixins.js #

let sayHiMixin = {
  sayHi() {
    alert(`Hello ${this.name}`);
  }
}


let sayByeMixin = {
  sayBye() {
    alert(`Bye ${this.name}`);
  }
}


class User {
  constructor(name) {
    this.name = name;
  }
}

// copy the methods
Object.assign(User.prototype, sayHiMixin);
Object.assign(User.prototype, sayByeMixin);


const user = new User("Dude")

user.sayHi()
user.sayBye()

On gists

Fake slide pure css

CSS CSS trick

index.html #

<!-- DEMO: https://jsbin.com/goyapuworo/edit?html,css,output -->

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Fake slide by me</title>
	<style>
	.grid {
	
	display: flex;
	translate: 0;
	transition: 300ms;
}

.grid > div {
	width: calc(100% - 4rem);
	flex-shrink: 0;
	padding: 2rem;
}

.grid > div:first-child {
	background: pink;
}

.grid > div:first-child + *{
	background: lime;
}

article 
{
	border: 2px solid green;
	overflow: hidden;
}

input {
	margin-bottom: 20px;
}

input:checked + article .grid {
	translate: -100%;
}
	</style>
</head>
<body>
	
	<input type="checkbox">

	<article>
	<div class="grid">
		<div class="col">AA</div>
		<div class="col">BB</div>
	</div>
	</article>
	
</body>
</html>

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