<?php
// 1) single fns ..
$data = [
'400,22 je super cislo a neobsahuje ani @',
'Symbol @ je bezvič',
'@@@ nebo XXX?',
'Tady nic',
];
$NaNicToNeplati = function() {
return null;
};
$NumberDashToDot = function($value) {
if (preg_match('~\d+,\d+~', $value)) {
return str_replace(',', '.', $value);
}
return null;
};
$RemoveZavinac = function($value) {
if (preg_match('~@~', $value)) {
return str_replace('@', '', $value);
}
return null;
};
$RemoveXXX = function($value) {
if (preg_match('~X~', $value)) {
return str_replace('X', 'maleX', $value);
}
return null;
};
$filters = [
'NumberDashToDot' => $NumberDashToDot,
'NaNicToNeplati' => $NaNicToNeplati,
'RemoveZavinac' => $RemoveZavinac,
'RemoveXXX' => $RemoveXXX,
];
$evaluate = function($data, $filters) {
$results = [];
foreach ($data as $value) {
$origValue = $value;
$result = [
'met' => [],
'notMet' => [],
'transformations' => [],
'origValue' => $value,
'finalValue' => null,
];
foreach ($filters as $fnName => $fnClosure) {
if ($valueNormalized = $fnClosure($value)) {
$value = $valueNormalized;
$result['met'][] = $fnName;
$result['transformations'][$fnName] = $valueNormalized;
} else {
$result['notMet'][] = $fnName;
}
}
$result['finalValue'] = $value;
$results[] = $result;
}
return $results;
};
$results = $evaluate($data, $filters);
echo "<pre>";
print_r($results);
echo "</pre>";
// OOP
class DataTransformer
{
private $filters;
public function __construct(array $filters)
{
$this->filters = $filters;
}
public function transform(array $data): array
{
return array_map(function ($value) {
$result = [
'met' => [],
'notMet' => [],
'transformations' => [],
'origValue' => $value,
'finalValue' => null,
];
foreach ($this->filters as $filter) {
if ($filter->apply($value)) {
$result['met'][] = $filter->getName();
$result['transformations'][$filter->getName()] = $value;
} else {
$result['notMet'][] = $filter->getName();
}
}
$result['finalValue'] = $value;
return $result;
}, $data);
}
}
interface FilterInterface
{
public function apply(string &$value): bool;
public function getName(): string;
}
class NumberDashToDotFilter implements FilterInterface
{
public function apply(string &$value): bool
{
if (preg_match('~\d+,\d+~', $value)) {
$value = str_replace(',', '.', $value);
return true;
}
return false;
}
public function getName(): string
{
return 'NumberDashToDot';
}
}
class RemoveZavinacFilter implements FilterInterface
{
public function apply(string &$value): bool
{
if (strpos($value, '@') !== false) {
$value = str_replace('@', '', $value);
return true;
}
return false;
}
public function getName(): string
{
return 'RemoveZavinac';
}
}
// Přidat další filtry podle potřeby
$data = [
'400,22 je super cislo a neobsahuje ani @',
'Symbol @ je bezvič',
'@@@ nebo XXX?',
'Tady nic',
];
$filters = [
new NumberDashToDotFilter(),
new RemoveZavinacFilter(),
// Přidat další filtry podle potřeby
];
$transformer = new DataTransformer($filters);
$results = $transformer->transform($data);
echo "<pre>";
print_r($results);
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)
}
*/
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()
<!-- 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>
<?php
/*
if (isset($a['b'])) {
$x = $a['b'];
echo $x;
}
*/
if ($x = ($a['b'] ?? null)) {
echo $x;
}
// 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]
},
}
// 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);
/*
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, [])
// 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 }), {});
/* 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;
}