/ Gists

Gists

On gists

Stacks / Queue

JavaScript

stack.js #

class Stack {
    #items = []

    push(item) {
        this.#items.push(item)
    }

    pop() {
        if(this.isEmpty()) return 'Underflow'
        return this.#items.pop()
    }

    isEmpty() {
        return this.#items.length === 0
    }

    get length() {
        return this.#items.length
    }

    getItems() {
        return this.#items
    }

    prettify() {
        let resultString = ''
        for(let i = 0; i < this.#items.length; i++)
            resultString += this.#items[i] + ' '
        return resultString
    }
}

let foods = new Stack

foods.push('pizza')
foods.push('hamburger')
foods.push('kebab')
foods.push('kufte')

console.log(foods.length) // 4

console.log(foods.getItems()) // [ 'pizza', 'hamburger', 'kebab', 'kufte' ]

console.log(foods.prettify()) // pizza hamburger kebab kufte

console.log(foods.pop()) // kufte
console.log(foods.pop()) // kebab
console.log(foods.pop()) // hamburger
console.log(foods.pop()) // pizza

console.log(foods.length) // 0

On gists

Simple global state hook aka composable

Vue.js

state.js #

import { ref, readonly } from 'vue';

const sharedVar = ref(false);

const toggleOutside = () => {
  sharedVar.value = !sharedVar.value;
};

export const useTestState = () => {
  const toggleInside = () => {
    sharedVar.value = !sharedVar.value;
  };

  return {
    sharedVar: readonly(sharedVar),
    toggleOutside,
    toggleInside,
  };
};

On gists

Animations

Tailwind CSS

demo.html #

<div class="flex justify-around p-20">
  <!-- Wiggle animation -->
  <div class="flex flex-col gap-4">
    <span>wiggle</span>
    <div class="h-16 w-16 animate-wiggle rounded-md bg-pink-400"></div>
  </div>

  <!-- heartBeat animation -->
  <div class="flex flex-col gap-4">
    <span>heartBeat</span>
    <div class="h-16 w-16 animate-heartBeat rounded-md bg-blue-400"></div>
  </div>

  <!-- flipHorizontal animation -->
  <div class="flex flex-col gap-4">
    <span>flipHorizontal</span>
    <div class="h-16 w-16 animate-hflip rounded-md bg-orange-400 text-center"><span>Flip H</span></div>
  </div>

  <!-- flipVertical animation -->
  <div class="flex flex-col gap-4">
    <span>flipVertical</span>
    <div class="h-16 w-16 animate-vflip rounded-md bg-indigo-400 text-center"><span>Flip V</span></div>
  </div>
</div>

<div class="flex justify-around p-20">
  <!-- Swing animation -->
  <div class="flex flex-col gap-4">
    <span>swing</span>
    <span class="animate-swing text-3xl font-extrabold text-red-400">Swinging</span>
  </div>

  <!-- rubberBand animation -->
  <div class="flex flex-col gap-4">
    <span>rubberBand</span>
    <span class="animate-rubberBand text-3xl font-extrabold text-violet-400">Stretching</span>
  </div>

  <!-- flash animation -->
  <div class="flex flex-col gap-4">
    <span>flash</span>
    <span class="animate-flash text-3xl font-extrabold text-orange-800">Flashing</span>
  </div>
</div>

<div class="flex justify-around p-20">
  <!-- headShake animation -->
  <div class="flex flex-col gap-4">
    <span>headShake</span>
    <span class="animate-headShake text-3xl font-extrabold text-green-500">Shaking Heads</span>
  </div>

  <!-- wobble animation -->
  <div class="flex flex-col gap-4">
    <span>wobble</span>
    <span class="animate-wobble text-3xl font-extrabold text-blue-500">Wobbling</span>
  </div>

  <!-- wobble animation -->
  <div class="flex flex-col gap-4">
    <span>jello</span>
    <span class="animate-jello text-3xl font-extrabold text-purple-400">Jello</span>
  </div>
</div>

On gists

Before, Prepend, Append, After (insertAdjacentElement) ... (*Text, *Html)

JavaScript

demo.html #

<!-- https://jsbin.com/pajoyovilu/3/edit?html,css,js,console,output -->


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
	
	
	<button onclick="placeTo('beforebegin')">before</button>
	<button onclick="placeTo('afterbegin')">prepend</button>
	<button onclick="placeTo('beforeend')">append</button>
	<button onclick="placeTo('afterend')">after</button>
	
	
	<div id="x">
		<div>START</div>
		<AA>aa</AA>
		<BB>bb</BB>
		<CC>cc</CC>
		<div>END</div>
		
	</div>
</body>
</html>

On gists

Card number - space after each 4 digit & only digit control

Vue.js

component.vue #

<!-- https://javascript.plainenglish.io/vue-get-input-value-206d5adc832c -->

<template>
  <div id="app">
    <input
      type="text"
      :value="cardNo"
      placeholder="Card number"
      @input="handleInput"
      @keypress="handleKeyPress"
    />
    <br />
  </div>
</template>
<script>
export default {
  data() {
    return {
      cardNo: '',
    };
  },
  methods: {
    handleInput(event) {
      this.cardNo = event.target.value
        // Remove spaces from previous value
        .replace(/\s/g, '')
        // Add a space after every set of 4 digits
        .replace(/(.{4})/g, '$1 ')
        // Remove the space after the last set of digits
        .trim();
    },
    handleKeyPress(event) {
      const num = Number(event.key);
      const value = event.target.value;
      // Only allow 16 digits
      if ((!num && num !== 0) || value.length >= 16 + 3) {
        event.preventDefault();
      }
    },
  },
};
</script>

On gists

Debounced method in Vue (settimeout), fetch with cors mode

JavaScript Vue.js

example.js #

  methods: {
    search() {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.findSong()
      }, 500)
    },

    async findSong() {
      let headers = new Headers()
      headers.append('Content-Type', 'application/json')
      headers.append('Accept', 'application/json')
      headers.append('Origin', 'http://vue3.rjwebdesign.cz')
      headers.append('GET', 'POST', 'OPTIONS')

      let q = encodeURI(this.q)
      if (!this.q) {
        return
      }

      //console.log(q)
      // return

      const response = await fetch(`https://itunes.apple.com/search?term=${q}&limit=50`, {
        mode: 'cors',
        method: 'POST',
        headers: headers
      }).catch(err => console.log(err))

      const data = await response.json()
      this.songs = data.results.filter(item => item.kind == 'song')
      console.log(this.songs)
    },

On gists

ES6: Template system in literal

JavaScript ES 6

example.js #

let post = {
    title: 'JavaScript Template Literals',
    excerpt: 'Introduction to JavaScript template literals in ES6',
    body: 'Content of the post will be here...',
    tags: ['es6', 'template literals', 'javascript']
};


let {title, excerpt, body, tags} = post;

let postHtml = `<article>
<header>
    <h1>${title}</h1>
</header>
<section>
    <div>${excerpt}</div>
    <div>${body}</div>
</section>
<footer>
    <ul>
      ${tags.map(tag => `<li>${tag}</li>`).join('\n      ')}
    </ul>
</footer>`;

window['out'].innerHTML = postHtml

On gists

Promises, Await / Async, Callbacks

JavaScript

demo1.html #

<!--https://www.loginradius.com/blog/engineering/callback-vs-promises-vs-async-await/-->

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script type="module">
            // 1 Promises - way 1

            // Promise1
            const promise1 = new Promise((resolve, reject) => {
                const condition = true;
                if (condition) {
                    setTimeout(function () {
                        resolve('Promise is resolved!'); // fulfilled
                    }, 300);
                } else {
                    reject('Promise is rejected!');
                }
            });

            // Promise2
            const promise2 = function () {
                return new Promise(function (resolve, reject) {
                    const message = `Hi, How are you!`;

                    resolve(message);
                });
            };

            // Test = chaining
            const testPromise = function () {
                promise1
                    .then(promise2)
                    .then(successMsg => {
                        console.log('Success:' + successMsg);
                    })
                    .catch(errorMsg => {
                        console.log('Error:' + errorMsg);
                    });
            };

            testPromise();

            // 2 Async / Await  = way 2
            async function testPromise2() {
                try {
                    let message = await promise1;
                    let message2 = await promise2();
                    console.log(message);
                    console.log(message2);
                } catch (error) {
                    console.log('Error:' + error.message);
                }
            }

            // we call it ...
            (async () => {
                await testPromise2();
            })();
        </script>
    </body>
</html>

On gists

Multi-file single-file components (external files)

Vue.js

vuecomp.vue #

<!-- A "single" file component -->
<template src="./template.html"></template>
<script src="./script.js"></script>
<style scoped src="./styles.css"></style>

On gists

How to make a variable created outside of Vue reactive - Options API

Vue.js

example.js #

// options API

const externalVariable = getValue();

export default {
  data() {
    return {
      reactiveVariable: externalVariable,
    };
  }
};