/ Gists

Gists

On gists

Javascript function is object

JavaScript

fn.js #

/*
  function in javascript is object and we can store what ever inside 
*/

function x()
{
  console.log('im x')
}

x.$version = '1.3.21'
x.callback = () => { console.log('what ever')}


console.log(x.$version);
x.callback();

On gists

Vue.js - Suspense

Vue.js

Suspense.vue #

<template>
  <div>
    <h1>Async Component Example</h1>
    <suspense>
      <template #default>
        <AsyncComponent />
      </template>
      <template #fallback>
        <LoadingSpinner />
      </template>
    </suspense>
  </div>
</template>

<script setup>
import { defineAsyncComponent } from 'vue';

const AsyncComponent = defineAsyncComponent(() =>
  import('./AsyncComponent.vue')
);
</script>

On gists

Vue.js - Renderless pattern

renderless.vue #

<!-- MouseTracker.vue -->
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
  
const x = ref(0)
const y = ref(0)

const update = e => {
  x.value = e.pageX
  y.value = e.pageY
}

onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
</script>

<template>
  <slot :x="x" :y="y"/>
</template>

<!-- Usage: -->
<template>
	<MouseTracker v-slot="{ x, y }">
  	Mouse is at: {{ x }}, {{ y }}
	</MouseTracker>
</template>



<!-- 1) composable -->
<script setup>
  import { ref } from "vue";

  const checkbox = ref(false);

  const toggleCheckbox = () => {
    checkbox.value = !checkbox.value;
  };
</script>

<!--1) Usage in component -->
<template>
  <div class="comp">
    <label class="switch">
      <input type="checkbox" :value="checkbox" @click="toggleCheckbox" />
      <div class="slider rounded" :class="checkbox ? 'active' : ''"></div>
    </label>
  </div>
</template>

<script setup>
  import { useCheckboxToggle } from "./composables/useCheckboxToggle";

  const { checkbox, toggleCheckbox } = useCheckboxToggle();
</script>



<!-- 2) instead composable we can use renderless component -->
<template>
  <slot :checkbox="checkbox" :toggleCheckbox="toggleCheckbox"></slot>
</template>

<script setup>
  import { ref } from "vue";

  const checkbox = ref(false);

  const toggleCheckbox = () => {
    checkbox.value = !checkbox.value;
  };
</script>


<!--2) many different usage, depends on us and styles -->
<template>
  <slot :checkbox="checkbox" :toggleCheckbox="toggleCheckbox"></slot>
</template>

<script setup>
  import { ref } from "vue";

  const checkbox = ref(false);

  const toggleCheckbox = () => {
    checkbox.value = !checkbox.value;
  };
</script>



<!-- useFetch -->
// fetch.js
import { ref, watchEffect, toValue } from 'vue'

export function useFetch(url) {
  const data = ref(null)
  const error = ref(null)

  const fetchData = () => {
    // reset state before fetching..
    data.value = null
    error.value = null

    fetch(toValue(url))
      .then((res) => res.json())
      .then((json) => (data.value = json))
      .catch((err) => (error.value = err))
  }

  watchEffect(() => {
    fetchData()
  })

  return { data, error }
}

On gists

Vue.js - Provide pattern

Provider.vue #

<!-- https://www.patterns.dev/vue/data-provider -->

<!-- Provider.vue -->
<template>
  <slot :data="data" :loading="loading"></slot>
</template>

<script setup>
  import { ref, reactive } from "vue";

  const API_ENDPOINT_URL = "https://official-joke-api.appspot.com/random_joke";

  const data = reactive({
    setup: null,
    punchline: null,
  });
  const loading = ref(false);

  const fetchJoke = async () => {
    loading.value = true;

    const response = await fetch(API_ENDPOINT_URL);
    const responseData = await response.json();

    data.setup = responseData.setup;
    data.punchline = responseData.punchline;
    loading.value = false;
  };

  fetchJoke();
</script>


<!-- Usage: AnyComponent.vue -->
<template>
  <DataProvider v-slot="{ data, loading }">
    <div class="joke-section">
      <p v-if="loading">Joke is loading...</p>
      <p v-if="!loading">{{ data.setup }}</p>
      <p v-if="!loading">{{ data.punchline }}</p>
    </div>
  </DataProvider>
</template>

<script setup>
  import DataProvider from "./components/DataProvider.vue";
</script>



<!-- Could be realized by Composable -->
<!-- UseJoke.js -->
import { ref, reactive } from "vue";

const API_ENDPOINT_URL = "https://official-joke-api.appspot.com/random_joke";

export function useGetJoke() {
  const data = reactive({
    setup: null,
    punchline: null,
  });
  const loading = ref(false);

  const fetchJoke = async () => {
    loading.value = true;

    const response = await fetch(API_ENDPOINT_URL);
    const responseData = await response.json();

    data.setup = responseData.setup;
    data.punchline = responseData.punchline;
    loading.value = false;
  };

  fetchJoke();

  return { data, loading };
}


<!-- Usage -->
<template>
  <div class="joke-section">
    <p v-if="loading">Joke is loading...</p>
    <p v-if="!loading">{{ data.setup }}</p>
    <p v-if="!loading">{{ data.punchline }}</p>
  </div>
</template>

<script setup>
  import { useGetJoke } from "./composables/useGetJoke";

  const { data, loading } = useGetJoke();
</script>

On gists

Convert Vue component to Web component

Web components Vue.js

HelloWorld.ce.vue #

<!-- ce je jen interni oznaceni ze to bude custom element = web component -->
<script setup>
defineProps({
  msg: {
    type: String,
    required: true,
    default: 'AAA'
  }
})
</script>

<template>
  <div>{{ msg }}</div>
</template>

<style scoped>
h1 {
  font-weight: 500;
  font-size: 2.6rem;
  position: relative;
  top: -10px;
}

h3 {
  font-size: 1.2rem;
}

.greetings h1,
.greetings h3 {
  text-align: center;
}

@media (min-width: 1024px) {
  .greetings h1,
  .greetings h3 {
    text-align: left;
  }
}
</style>

On gists

Advanced usage of CASE WHEN THEN

MySql MySql - advanced

when-then.sql #

-- https://towardsdev.com/sql-case-statement-with-code-examples-04f77dab8d5a

-- 1. Simple case
SELECT
    order_id,
    CASE customer_id
        WHEN 1 THEN 'Premium'
        WHEN 2 THEN 'Gold'
        WHEN 3 THEN 'Silver'
        ELSE 'Regular'
    END AS customer_type
FROM orders;


-- 2. Searched CASE Statement
SELECT
    order_id,
    CASE
        WHEN order_amount > 1000 THEN 'High'
        WHEN order_amount > 500 THEN 'Medium'
        ELSE 'Low'
    END AS order_priority
FROM orders;

-- 3. Using CASE in WHERE Clause
SELECT *
FROM customers
WHERE CASE
    WHEN country = 'USA' THEN sales_region = 'North America'
    WHEN country = 'UK' THEN sales_region = 'Europe'
    ELSE FALSE
END;

-- 4. Using CASE with Aggregate Functions
SELECT
    department,
    COUNT(CASE WHEN salary > 50000 THEN 1 END) AS high_salary_count,
    COUNT(CASE WHEN salary <= 50000 THEN 1 END) AS low_salary_count
FROM employees
GROUP BY department;


-- 5. Nesting CASE Statements
SELECT
    order_id,
    CASE
        WHEN payment_status = 'paid' THEN
            CASE
                WHEN shipping_status = 'shipped' THEN 'Delivered'
                ELSE 'Processing'
            END
        ELSE 'Pending'
    END AS order_status
FROM orders;

-- 6. Using CASE in JOIN Conditions
SELECT
    o.order_id,
    o.order_date,
    c.customer_name
FROM orders o
JOIN customers c
ON CASE
    WHEN o.customer_id = 1 THEN c.customer_id = o.customer_id
    WHEN o.customer_id = 2 THEN c.country = 'USA'
    ELSE c.country = 'UK'
END;


-- INSERT
INSERT INTO employees (employee_id, name, salary)
VALUES
 (101, 'John Doe', 
 CASE
 WHEN department = 'Engineering' THEN 80000
 WHEN department = 'Marketing' THEN 70000
 ELSE 60000
 END);

On gists

Composable return values - destruct - keep reactivity

Vue.js

Example.js #

// Composable
const useBurger = () => {
  const lettuce = ref(true);
  const ketchup = ref(true);
return {
  lettuce,
  ketchup,
}


// Component
setup() {
  // We can destructure but still keep our reactivity
  const { ketchup } = useBurger();
  watchEffect(() => console.log(ketchup.value));
  return {
    ketchup,
    removeKetchup: () => ketchup.value = false
  };
}



// If you don't want to destructure the values, you can always wrap it in reactive and it
// will be converted to a reactive object

// Component
setup() {
    // Wrap in `reactive` to make it a reactive object
    const burger = reactive(useBurger());
    watchEffect(() => console.log(burger.ketchup));
        return {
        burger,
        removeKetchup: () => burger.ketchup = false
    }
}



// destruct needs toRefs
const refBurger = ref({ lettuce: true });
const reactiveBurger = reactive({ lettuce: true });

const { lettuce } = toRefs(refBurger.value);
const { lettuce } = toRefs(reactiveBurger);

On gists

Baby wolf codes - advanced JS tips

Popular ⭐ JavaScript

tips.js #

// Destructure into multiple variables
const obj = { val: 1 };
const { val: a, val: b, val } = obj;

console.log(a); // -> 1
console.log(b); // -> 1
console.log(val); // ->



// Chaining catch in Promise
const somePromise = async () => Promise.reject('error');
somePromise()
    .then(e => {
        //
    })
    .catch(e => {
        throw new Error('error happened');
    })
    .catch(e => {
        console.log('hi ' + e); // hi Error
    });


// Multiple handlers for Promise
async function add(a, b) {
    return a + b;
}
const promise = add(1, 2);
promise.then(e => `Result 1: ${e}`);
promise.then(e => `Result 2: ${e}`);
// -> Result 1: 3
// -> Result 2: 3



// Mixed promise handler liky try catch
async function someFunction() {
    const res = await somePromise().catch(err => {
        /* handle */
    });
}



// Advanced default params  
function test({ val = -1 } = {}) {
    console.log(val);
}
test(); // -> -1
test({}); // -> -1
test({ val: 123 }); // -> 12


// Generate compact numbers
const formatter = Intl.NumberFormat('en',{ notation: 'compact' });
formatter.format('123'); // -> 123
formatter.format('1234'); // -> 1.2K
formatter.format('1235678'); // -> 1.2M
formatter.format('1235678901'); // -> 1.2B


//Default parameters previously declared
function test(x, y, z = x + y) {
    console.log(z);
}
test(1, 1, 1); // -> 1
test(1, 1); // -> 2



// Additional arguments to setTimeout()
function callback(value) {
    console.log(value);
}
setTimeout(callback, 1000, 5);
// -> Prints '5' after 1 second


// matchMedia
const query = window.matchMedia('(max-width: 600px)');
console.log('init -> ' + +query.matches)
query.addEventListener('change', event => {
console.log('change -> ' + +query.matches)
})


// promises
async function add(a, b) {
return a + b;
}
function addAndDouble(a, b) {
return add(a, b).then(res => res * 2);
}
addAndDouble(1, 2).then(res => {
console.log(res); // -> 6
})

On gists

Latte component

Nette Nette-Latte

any.latte #

<!-- component definition  -->
{define badge, bool $show = true, string $title = '', $class = null}
	<span class="badge ms-2 font-size-small {$class ?? 'bg-body-secondary text-body'}" n:if="$show" title="{$title}">
		{block content}{/block}
	</span>
{/define}


<!-- usage -->
{embed badge, $client !== null, 'Uhrazeno'}
	{block content}
		<i class="mdi mdi-check text-success"></i>
		{$client->totalInvoicePricePaid|price:0}
	{/block}
{/embed}

On gists

Dynamic Vue.js component in runtime

Vue.js

Dynamic.vue #

<template>
  <h1>test</h1>
  <component :is="dynamicComponent" />
</template>


<script setup>
import { computed} from 'vue'

const dynamicComponent = computed(() => {

  let template = `
    <h3>Toto je dynamic component</h3>
    <p>Nejaky text</p>
  `

  return { template }

})
</script>

<!--/* musi to byt jako bundle vue .. build, ne runtime vue   */-->