/ Gists

Gists

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

Sledování změn na $refs prvku

Popular ⭐ Vue.js

Foo.vue #

<template>
    <div ref="el" style="height: 70px" :style="computedStyles">
        <slot />
    </div>

    <hr />
    height {{ height }}
    <br />
    Computed {{ computedHeight }}
    <hr />

    <button @click="changeHeight(150)">150</button>
    <button @click="changeHeight(200)">200</button>
    <button @click="changeHeight(250)">250</button>
</template>

<script>
export default {
    data() {
        return {
            height: null,
            isMounted: false,
        };
    },
    computed: {
        computedStyles() {
            if (this.isMounted && this.height) return { height: this.computedHeight, background: 'limegreen' };
            return { background: 'pink' };
        },
        computedHeight() {
            if (this.isMounted && this.height) return this.height + 'px';

            return null;
        },
    },
    methods: {
        changeHeight(h) {
            //console.log('BEFORE', this.height);
            this.height = h;
            //console.log('AFTER', this.height);
        },

        observeElement() {
            const el = this.$refs.el;
            const observer = new MutationObserver(mutationsList => {
                for (const mutation of mutationsList) {
                    if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                        console.log('Element style changed:', el.style.height);
                    }
                }
            });

            observer.observe(el, { attributes: true });
        },
    },
    mounted() {
        this.isMounted = true;
        this.height = this.$refs.el.style.height;
        this.observeElement(); // Spustíme sledování změn výšky elementu
    },
};
</script>

On gists

Globální funkce / proměnná + instalace do Vue 3

Vue.js

AnyFile.js #

export const filter = {
  install: (vue) => {
    vue.config.globalProperties.$f = (name) => {
      console.log('CUSSS ' + name);
    };
  },
};

On gists

Collection (filter, map, sort ... in one)

PHP Libs PHP

Collection.php #

<?php

/* https://betterprogramming.pub/how-to-make-your-php-code-beautiful-with-chainable-methods-83d8832b1b16 */

class Collection
{
    private $array;
    public function __construct($array)
    {
        $this->array = $array;
    }
    public function filter($callback)
    {
        $this->array = array_filter($this->array, $callback);
        return $this;
    }
    public function map($callback)
    {
        $this->array = array_map($callback, $this->array);
        return $this;
    }
    public function sort($callback)
    {
        usort($this->array, $callback);
        return $this;
    }
    public function execute()
    {
        return $this->array;
    }
}


$characters = new Collection([
    'Maggie Simpson',
    'Edna Krabappel',
    'Marge Simpson',
    'Lisa Simpson',
    'Moe Szyslak',
    'Waylon Smithers',
    'Homer Simpson',
    'Bart Simpson'
]);
$simpsons = $characters
    ->filter(function ($character) {
        return preg_match('/^.+\sSimpson$/', $character);
    })
    ->map(function ($character) {
        return str_replace(' Simpson', '', $character);
    })
    ->sort(function ($a, $b) {
        return strcasecmp($a, $b);
    })
    ->execute();
var_dump($simpsons); // ['Bart', 'Homer', 'Lisa', 'Maggie', 'Marge']

On gists

Access to instance

Vue.js

any-composable-hook.js #

import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
const $t = instance.appContext.app.config.globalProperties.$t

const availableFromFormatter = n => {
  if (n > 30) return $t('více jak měsíc do naskladnění')
  if (n <= 3) return $t('méně jak 3 dny do naskladnění')
  if (n <= 7) return $t('méně jak 7 dnů do naskladnění')
  if (n <= 14) return $t('méně jak 14 dnů do naskladnění')
  if (n <= 30) return $t('méně jak měsíc do naskladnění')

  return $t('neznámá doba do naskladnění')
}

export { availableFromFormatter }

On gists

Check column in table if exists

MySql MySql tricks

check-column.sql #

SELECT COUNT(*) INTO @cnt FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'transport_type' AND column_name = 'measure_distance';

SET @q = IF(@cnt <= 0, 
"ALTER TABLE transport_type ADD COLUMN measure_distance TINYINT(1) NULL DEFAULT NULL COMMENT 'Měřit vzdálenost' AFTER delivery_holiday",
'select \'Column exists\' status');

 PREPARE stmt from @q;
 EXECUTE stmt;
 DEALLOCATE PREPARE stmt;

On gists

Kometa comments - more ways to refactor

Refactoring PHP

comments.php #

<?php

//  if hell
if ($commentRow->type == 'forum')
{
    $baseUrl = '/diskuse';
}

if ($commentRow->type == 'clanek')
{
    $baseUrl = '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
}

if ($commentRow->type == 'zapas')
{
    $baseUrl = '/zapas/' .  $commentRow->rellID;
}

if ($commentRow->type == 'stranka')
{
    $baseUrl = '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
}

\Redirect::url($baseUrl .'?l='.$newPageNo.'&parentNode='.$commentRow->parent_sibling_id.'#cmt-'.$commentRow->id);


// map table
$baseUrlMap = [
    'forum' => '/diskuse',
    'clanek' => '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID),
    'zapas' => '/zapas/' .  $commentRow->rellID,
    'stranka' => '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID),
];

$baseUrl = '';

if (isset($baseUrlMap[$commentRow->type])) {
    $baseUrl = $baseUrlMap[$commentRow->type];
}



// 3 callback fns
$baseUrlMap = [
    'forum' => '/diskuse',
    'clanek' => function() use ($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    },
    'zapas' => function() use ($commentRow) {
        return '/zapas/' . $commentRow->rellID;
    },
    'stranka' => function() use ($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    },
];

$baseUrl = '';

if (isset($baseUrlMap[$commentRow->type])) {
    if (is_callable($baseUrlMap[$commentRow->type])) {
        $baseUrl = $baseUrlMap[$commentRow->type]();
    } else {
        $baseUrl = $baseUrlMap[$commentRow->type];
    }
}



// Factories

$baseUrl = '';

interface UrlGenerator {
    public function generateUrl($commentRow);
}

class ForumUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/diskuse';
    }
}

class ClanekUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class ZapasUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/zapas/' .  $commentRow->rellID;
    }
}

class StrankaUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

$generators = [
    'forum' => new ForumUrlGenerator(),
    'clanek' => new ClanekUrlGenerator(),
    'zapas' => new ZapasUrlGenerator(),
    'stranka' => new StrankaUrlGenerator(),
];

$commentType = $commentRow->type;
if (isset($generators[$commentType])) {
    $baseUrl = $generators[$commentType]->generateUrl($commentRow);
}


// fns for all with argument
$baseUrlMap = [
    'forum' => function($row) {
        return '/diskuse';
    },
    'clanek' => function($row) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $row->rellID);
    },
    'zapas' => function($row) {
        return '/zapas/' .  $row->rellID;
    },
    'stranka' => function($row) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $row->rellID);
    },
];

$commentType = $commentRow->type;
if (isset($baseUrlMap[$commentType])) {
    $baseUrl = $baseUrlMap[$commentType]($commentRow);
}



// FactoryGenerator

interface UrlGenerator {
    public function generateUrl($commentRow);
}

class ForumUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/diskuse';
    }
}

class ClanekUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class ZapasUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/zapas/' .  $commentRow->rellID;
    }
}

class StrankaUrlGenerator implements UrlGenerator {
    public function generateUrl($commentRow) {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class UrlGeneratorFactory {
    public static function createGenerator($type): UrlGenerator {
        $generators = [
            'forum' => new ForumUrlGenerator(),
            'clanek' => new ClanekUrlGenerator(),
            'zapas' => new ZapasUrlGenerator(),
            'stranka' => new StrankaUrlGenerator(),
        ];

        return $generators[$type] ?? null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}


// Dalsi o neco lepsi
class UrlGeneratorFactory {
    public static function createGenerator($type): ?UrlGenerator {
        $generators = [
            'forum' => function () {
                return new ForumUrlGenerator();
            },
            'clanek' => function () {
                return new ClanekUrlGenerator();
            },
            'zapas' => function () {
                return new ZapasUrlGenerator();
            },
            'stranka' => function () {
                return new StrankaUrlGenerator();
            },
        ];

        return $generators[$type] ? $generators[$type]() : null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}



// Moje verze, lazy, nejefektivnejsi

class UrlGeneratorFactory {
    public static function createGenerator($type): ?UrlGenerator {
        $generators = [
            'forum' => ForumUrlGenerator::class,
            'clanek' => ClanekUrlGenerator::class,
            'zapas' => ZapasUrlGenerator::class,
            'stranka' => StrankaUrlGenerator::class,
        ];

        if (isset($generators[$type])) {
            return new $generators[$type]();
        }

        return null;
    }
}

$commentType = $commentRow->type;
$generator = UrlGeneratorFactory::createGenerator($commentType);

if ($generator) {
    $baseUrl = $generator->generateUrl($commentRow);
}




// Claude 3.5
// Strategy pattern
<?php

interface CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string;
}

class ForumRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/diskuse';
    }
}

class ArticleRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class MatchRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/zapas/' . $commentRow->rellID;
    }
}

class PageRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class CommentRedirectHandler {
    private array $strategies = [];

    public function addStrategy(string $type, string $strategyClass): void {
        if (!is_subclass_of($strategyClass, CommentRedirectStrategy::class)) {
            throw new \InvalidArgumentException("$strategyClass musí implementovat CommentRedirectStrategy");
        }
        $this->strategies[$type] = $strategyClass;
    }

    public function redirect(object $commentRow, int $newPageNo): void {
        if (!isset($this->strategies[$commentRow->type])) {
            throw new \InvalidArgumentException("Neznámý typ komentáře: {$commentRow->type}");
        }

        $strategyClass = $this->strategies[$commentRow->type];
        $strategy = new $strategyClass(); // Vytvoření instance až když je potřeba
        $baseUrl = $strategy->getBaseUrl($commentRow);

        $redirectUrl = sprintf(
            '%s?l=%d&parentNode=%d#cmt-%d',
            $baseUrl,
            $newPageNo,
            $commentRow->parent_sibling_id,
            $commentRow->id
        );

        \Redirect::url($redirectUrl);
    }
}

// Použití:
$handler = new CommentRedirectHandler();
$handler->addStrategy('forum', ForumRedirectStrategy::class);
$handler->addStrategy('clanek', ArticleRedirectStrategy::class);
$handler->addStrategy('zapas', MatchRedirectStrategy::class);
$handler->addStrategy('stranka', PageRedirectStrategy::class);

// Při zpracování komentáře:
$handler->redirect($commentRow, $newPageNo);




// slozitejsi vic tovaren
<?php

interface CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string;
}

class ForumRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/diskuse';
    }
}

class ArticleRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/clanky/' . \dibi::fetchSingle('SELECT seo FROM clanky WHERE id = %i', $commentRow->rellID);
    }
}

class MatchRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/zapas/' . $commentRow->rellID;
    }
}

class PageRedirectStrategy implements CommentRedirectStrategy {
    public function getBaseUrl(object $commentRow): string {
        return '/' . \dibi::fetchSingle('SELECT url FROM navigace WHERE id = %i', $commentRow->rellID);
    }
}

class CommentRedirectStrategyFactory {
    private array $strategies = [
        'forum' => ForumRedirectStrategy::class,
        'clanek' => ArticleRedirectStrategy::class,
        'zapas' => MatchRedirectStrategy::class,
        'stranka' => PageRedirectStrategy::class,
    ];

    public function createStrategy(string $type): CommentRedirectStrategy {
        if (!isset($this->strategies[$type])) {
            throw new \InvalidArgumentException("Neznámý typ komentáře: {$type}");
        }

        $strategyClass = $this->strategies[$type];
        return new $strategyClass();
    }
}

class CommentRedirectHandler {
    private CommentRedirectStrategyFactory $factory;

    public function __construct(CommentRedirectStrategyFactory $factory) {
        $this->factory = $factory;
    }

    public function redirect(object $commentRow, int $newPageNo): void {
        $strategy = $this->factory->createStrategy($commentRow->type);
        $baseUrl = $strategy->getBaseUrl($commentRow);

        $redirectUrl = sprintf(
            '%s?l=%d&parentNode=%d#cmt-%d',
            $baseUrl,
            $newPageNo,
            $commentRow->parent_sibling_id,
            $commentRow->id
        );

        \Redirect::url($redirectUrl);
    }
}

// Použití:
$factory = new CommentRedirectStrategyFactory();
$handler = new CommentRedirectHandler($factory);

// Při zpracování komentáře:
$handler->redirect($commentRow, $newPageNo);

On gists

lambda usort sorting

PHP

sort.php #

<?php
$x = [
	[
		'name' => 'BBB',
		'pts' => 30,
	],
	[
		'name' => 'AAA',
		'pts' => 90,
	],
	[
		'name' => 'CCC',
		'pts' => 40,
	]
];

usort($x, sortBy('pts', 'DESC')); // Změna zde - přidán parametr pro směr řazení

function sortBy($k, $sortOrder = 'ASC') // Změna zde - přidán druhý parametr s výchozí hodnotou ASC
{
	return function($a, $b) use ($k, $sortOrder)
	{
		$result = $a[$k] <=> $b[$k];
		return ($sortOrder === 'ASC') ? $result : -$result; // Změna zde - záporná hodnota pro DESC řazení
	};
}

echo "<pre>";
print_r($x);



//  2 way


function customSort($a, $b, $key, $sortOrder) {
    return $sortOrder === 'ASC' ? ($a[$key] <=> $b[$key]) : ($b[$key] <=> $a[$key]);
}

$key = 'name'; // Změňte podle sloupce, podle kterého chcete řadit
$sortOrder = 'ASC'; // Změňte na 'DESC' pro sestupné řazení

usort($x, function($a, $b) use ($key, $sortOrder) {
    return customSort($a, $b, $key, $sortOrder);
});

echo "<pre>";
print_r($x);

On gists

array_walk_recursive

PHP

demo.php #

<?php

$data = array(
    array('id' => 1, 'name' => 'John', 'children' => array('Alice', 'Bob')),
    array('id' => 2, 'name' => 'Jane', 'children' => array('Charlie', 'David')),
);

function add_last_name(&$value, $key) {
    if ($key === 'name') {
        $value .= ' Doe';
    }
}

array_walk_recursive($data, 'add_last_name');

print_r($data);

/*

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John Doe
            [children] => Array
                (
                    [0] => Alice Doe
                    [1] => Bob Doe
                )
        )
    [1] => Array
        (
            [id] => 2
            [name] => Jane Doe
            [children] => Array
                (
                    [0] => Charlie Doe
                    [1] => David Doe
                )
        )
)


*/