10/5/22

Getting started with docker

It is very simple to get started usig docker.
All you need to do-is download the docker desktop for your system
Once you get docker system running on your machine - you can start containers

docker run -d -p 80:80 docker/getting-started

Now you can see "docker/getting-started" container running on your machine

9/17/22

how to fetch data at nextJS

well - main thing application should do - is to display data.
so, you can fetch data from external source very simple:

export const getStaticProps = async () => {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users`)
  const users = await res.json();
  return {
    props: { users }
  }
}

export default function Home({ users }) {
  return <div>{users.map(({id, name}) => <div key={id}>{name}</div>)}</div>
}
The difference here - is that now you have no 'loading' time when page is empty.
That is because data loading happens on the server side

9/15/22

Some post about nextJs framework

Grate thing about this framework is that you can write the whole applicaiton using react on client and server side:
Hows that possible? you may ask
Thing is - the nextJs is first of all, nodejs application, and node uses same javascript language for writing api and also for write views. Views can be html and also they can include javascript, and in case of nextJs - they also include react.
So, how to start use it?
All you need to do for starting a nextJs project is to write following command in your terminal:

npx create-next-app my-mynext-app
after installation finished, navigate to app folder and run

npm run dev
browse to http://localhost:3000 and see your app is runing now!
The main advantage of nextJs framework is - SEO.
crawler can access pages more easily than at classic react app.
notice: you page already has react component:

export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Welcome</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title} onClick={() => alert('hi')}>
          Welcome!!!
        </h1>
      </main>
    </div>
    )
}
you can click on the title and see 'alert' appears

6/1/22

movies autocomplete exercise

At one of my interviews a was asked to create autocomplete that search movies and displays results.
I quickly created some input that handles changes and populates the state with the input:

export default function App() {
  const [term, setTerm] = useState("");
  useEffect(() => {
    // request logic...
  }, [term])
  return (
    <div className="App">
      <h1>
        <input
          onChange={(e) => setTerm(e.target.value)}
        />
      </h1>
      <h2>Term: {term}
    </div>
  );
}

the problem here, that changes populated imediately. and request sent for every character...
This can lead to performance issues and also - it is not exactly what user wants - he wants to start search after he finished to type the term...

Debounce

Instead we can take advantage of so called - debounce technique:
This means we only startnig the search after we indicated that user finished typing
If no typing happened for some period (one second in our case) only then we send a search request:

let debounceTimer;

const debounce = (callback, time) => {
  window.clearTimeout(debounceTimer);
  debounceTimer = window.setTimeout(callback, time);
};
export default function App() {
  const [term, setTerm] = useState("");
  useEffect(() => {
    // request logic...
  }, [term])
  return (
    <div className="App">
      <h1>
        <input
          onChange={(e) => debounce(() => {
           setTerm(e.target.value), 1000)}
          }
        />
      </h1>
      <h2>Term: {term}
    </div>
  );
}

5/23/22

Something about unit testing - After more than year!

It is importnat to understand what is a purpose of a unit test...
the prupose is to check only things that module (or component) is responsible of
example: if you have a toggle component like here:
code:

export function Toggle() {
  return (
    <label className="switch" role="toggle">
      <input type="checkbox" role="hidden-input" />
      <span className="slider round" />
    </label>
  );
}
you need to ask yourself: what is this thing responsible of? is it repsonsble for display nice slider and hide the real simple checkbox?
the answer is "yes", and this is exactly the thing you need to test:

5/7/20

Binary Tree Height Exersise

Recently i was at interview and asked following question:
Lest say, there is a binary tree like this:

Write a function which returns a highest level of the tree (in our exmaple is 3)

Solution

Here is a solution i came up with:
My assumption was that node structure has "name" property with node data and "children" with list of pointers to children nodes:


const tree = {
  name: 'a',
  children: [
    {
      name: 'b',
      children: [
        {
          name: 'd',
          children: []
        },
        {
          name: 'e',
          children: [{
               name: 'g',
               children: []
             },{
               name: 'h',
               children: []
             }        
          }]
        }       
      ]
    },
    {
      name: 'c',
      children: [
        {
          name: 'f',
          children: []
        },
        {
          name: 'g',
          children: []
        }        
      ]
    }    
  ]
}
Here is my solution:
I did it iterative way, because recursion can have space complexity issues

 
 function treeHeight(rootnode) {
    let nodes = [rootnode], maxLevel = 1; 
    nodes[0].level = 1;
    // loop through all the nodes
    while(nodes.length) {
       let node = nodes[0]
      
       if (node.children.length) {
         nodes = nodes.concat(node.children.map(ch => {ch.level = node.level + 1; return ch;})); /* if node has children - push them to the end of queue */
       }
       maxLevel = maxLevel < node.level ? node.level : maxLevel;    /* set maxLevel if some node level is bigger;*/
       nodes.shift(); /* remove the first node at each iteration */
    }
  
  	return maxLevel
}

5/5/20

Dont Afraid To Use Webpack

I must admit - im afraid of configuring the webpack by myself.
Im usually use create-react-app or angular-cli or some other boilerplate projects that have webpack configured already...
So the purpose of this post is: to create the simpliest configuration of webpack ever.
But first we need to ask - what is the main purpose of webpack anyway?
According to their site - webpack is module bundler Which means: a tool which concats all javascript modules (or files) into one big file. (that's all).

Experiment number one

Lets install webpack and play a little:

npm i -D webpack webpack-cli

Here is our first the webpack.config.js file:

const path = require('path');

module.exports = {
  entry: './myfile.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
};

At myfile.js lets put some very complicated code:

console.log('Hi@!')

And now lets run npx webpack

You can see that 'my-first-webpack.bundle.js' file created at 'dist' directory (wow!)
Note that it is minified and uglyfied (which is good...)

Experiment 2

Now - to something little more complicate: lets create another file, name it "other.js" and import it from the 'myfile':
other.js


export default Other = () => {
  console.log('Hi@!')
}

Again, run npx webpack
and we got only one 'my-first-webpack.bundle.js' in the dist (and yes it contains 'console.log' statement)

Experiment 3

Ok, you may say, but... how this webpack thing can help me with using some external library like, say React?
The answer is: lets try and see:

npm i react react-dom

Now lets change our myfile.js code to:

import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
  return React.createElement("div", {}, 'Hi!');
};
ReactDOM.render(React.createElement(App), document.getElementById("root"));

run npx webpack
Now create index file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    <script src="dist/my-first-webpack.bundle.js"></script>
</body>
</html>

double click it and... whoale!
We can see our React app is running

3/31/20

My Solution Of Rotate-Matrix question

Once i was asked to write a code which, given a matrix "rotates" it in a way that the "rows" become "columns".
For example:

const matrix = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]

Should become:

const result = [
  [1,4,7],
  [2,5,8],
  [3,6,9]
]

here is y solution for this challenge

function r(mat) {
  return mat.reduce((acc, row, idx) => {
     return [...acc, mat.map(itm => itm[idx])]
  }, [])
}
let res = r(matrix)
console.log({res})

Or it can be written as one row:

const r = mat => mat.reduce((acc, row, idx) => [...acc, mat.map(itm => itm[idx])], [])
let res = r(matrix)
console.log({res})

3/22/20

Non recursive way to write vibonachy sequence

It is very common interview question i see in many places: write a function which receives a serial number as a parameter and returns a fibonacci number.


// num -> 1 => 0
// num -> 2 => 1
// num -> 3 => 1
// num -> 4 => 2
// num -> 5 => 3
Usually i was quickly writing an answer using a recursion:

function f(num) {
  if (num === 0) return 0;
  if (num === 1 || num === 2 || num === 3) return 1;
  return f(num - 1) + f(num - 2);
}
console.log(f(5))

But ,since i found out that recursion has much more space complexity than iterative way, Here is that i come with trying to implement the fibonacci challenge using iterations (of while loop):

function f(num) { 
  if (num === 1)  return 0;
  if (num === 2 || num === 3) return 1;
  let counter = 4; // important to begin from 4, because we already taked care of 1 and 2 and 3 
  let result = 1, old = 1;
  while (counter <= num) {
    let temp = result;
    result = old + result;
    counter++;
    old = temp;    
  }
  return result;
}
let num = 1;
console.log(`${num} => ${f(num)}`)


3/1/20

Bfs

Question i was asked at one of my interviews:
You have a tree structure where each node has one or more leaf nodes (children)
Write a function which will write nodes of each level sorted in alternated order:
For example - given situation like this:

The output should be:
A, C, B, D, E, F, G, H
Note C, B is in reverse order!

My First Try

This question caught me unprepared (as usual).
My first step was to implement a tree structure in javascript (since my language is JS)


const tree = {
  name: 'a',
  children: [
    {
      name: 'b',
      children: [
        {
          name: 'd',
          children: []
        },
        {
          name: 'e',
          children: []
        },
        {
          name: 'f',
          children: []
        }       
      ]
    },
    {
      name: 'c',
      children: [
        {
          name: 'g',
          children: []
        },
        {
          name: 'h',
          children: []
        }        
      ]
    }    
  ]
}


My first idea was to store all the nodes im traversing through at some place outside the function (global variable) And use a recursion to loop through the nodes

const arr = {}
function f(tree, level = 0) {
  arr[level] = [...arr[level] || [], tree.name];
  (level % 2 ? tree.children: tree.children.reverse()).forEach(ch => f(ch, level+1))
}
f(tree)
console.log({arr}) // printing all nodes at the end

More Performant Way

Since i learned (in the hard way) that recursion is less performant than usual loop (and all the things you can do with recursion you can do as well using loop), i came up with following solution:


function f(tree, level = 0) {
   let queue = [], sortOrder = true;
   if (!level) queue.push(tree);
   // traversing through all the nodes of the tree
   while (queue.length) {
     let node = queue[0]; // moving to the next node (which is now the first)
     console.log(node.name); // printing node
     if (node.children.length){
        // populting the queue with current node's children
        queue = [...queue, ...node.children.sort((a,b) => (sortOrder? (a>b?1:-1) :(b>a?1:-1)))];        
     }
     
     sortOrder =! sortOrder;
     queue.shift(); // remove the first node from the queue (BFS, "F" is for first )

   }
   console.log('finished')
}
f(tree)

Note: im using here a "queue" data structure where members is added from one side and coming from other (FIFO)

2/5/20

Generators OR Interesting question i was asked at some interview

Question

Recently im going a lot to various interviews. So here is one interesting question i was asked:
Can you write the "adder" function that can be called multiple times and return sum of all numbers passed so far?
Example:
adder(1) // 1
adder(4) // 5
adder(2) // 7
Yes i answered, it is easy:


let store = 0;
function adder(num) {
  return store += num;
}
console.log(adder(1)) // 1
console.log(adder(6)) // 7

But interviewer asked:
And will it be possible not to use outer scope variables? (And i understood that answer is Yes)
Im not good at interviews in general, so the answer i finally got with, was:

let adder = (() => {
  let store = 0;
  return num  => store += num;
})()
console.log(adder(1)) // 1
console.log(adder(6)) // 7

Which is pretty much the same idea only the "store" is store inside the "Adder" function (actually it is more resembles the object with property to me)

Generators

After the interview (and actually even after i received a reject from this place) i had a sudden thought:what about generators - can they help me is such a problem?
What is generator?
according to the MDN site: Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
Which sounds exactly what is needed in my case, right?
After playing around i come with following code:


function* adder() {
 let i = 0
 while(true)  {
  i += yield i;
 }
}

const gen = adder();
gen.next()
console.log(gen.next(1).value);  // 1
console.log(gen.next(2).value);  // 3
console.log(gen.next(3).value);  // 6

Which is pretty much doing the same thing, only it has very different and complicated syntax...

Conclusion

In this post i tried to show how to build a function with a "state" (statefull). I solved a problem by using a closure;
Also i asked myself if generators can be helpfull here, and although the answer was not so clear, it was yet interesting to play with generators

2/1/20

My Implementation of Javascript "Bind"

Recently i was asked on some interview to implement "bind". So i think i will make a post dedicated to bind implementation.

What is a purpose of "bind" anyway?

Well, everybody knows that when you use a javascript you must use "this" keyword very carefully. In some cases - "this" (which called also execute context) can seem to "loose" its original meaning and have some unexpected value instead...

Example

Lets say you have a "Person" object in your code:


function Person(name) {
  this.name = name;
}
Person.prototype.showName = function() {
  console.log(this.name);
}

let person = new Person('Chubaka')
person.showName();
// will print "Chubaka" as expected

Simple and clear...
But!
What will happen if we will try to execute this method in response of some event, say clicking on document?

function Person(name) {
  this.name = name;
}
Person.prototype.showName = function() {
  console.log(this.name);
}

let person = new Person('Chubaka')
document.onclick = person.showName;
// will print "undefined" (WHYYYY???)

Why? because "this"(inside showName function) is no more populated with "person" object.
Instead (if we will try to debug and look closer at this "this") - we will find that like any event - the this now populated with the target of event(which is document)
This is where "bind" might be helpfull:
It attaches the context to function for the future execution:

let person = new Person('Chubaka')
document.onclick = person.showName.bind(person);
// will print "Chubaka" again

Implementation

Here is my implementation of bind (i called it "mybind")


  Function.prototype.mybind = function (context) {
    const that = this;// 'this' here is instance of "function" object
    return function() {// this function will be called in response to "click" event
      that.call(context)  // here the context will be passed           
    }
  }

Do we still Need "bind" in the era of ES6?

My answer is - No
Here is why:
You can write the same functionality using modern ES6 syntax:


  class Person {
    constructor(name) {
      this.name = name;
      this.showName = () => {
        console.log(this.name);
      }
    }
  }

let person = new Person('Chubaka')
document.onclick = person.showName; 
// chubaka is here again 
// (and no 'bind' needed)

See you in the next article!

1/15/20

Building shopping cart using angular8

Hi everybody!

This is my first 2020 post!
In this post i decided to show you how quickly you can build a shopping cart app using latest Angular8 and using as less code as possible...
Also
I will touch some interesting (at my point of view) consepts during this tutorial, like:

  1. Importace of plannig
  2. Which IDE is better
  3. One way data flow phylosophy
  4. Grid CSS
  5. reduce by example
So, lets start!

Planning

Of course before starting actually coding you need to have a clear picture in your mind of: how exactly the thing you want to build should look and how it should behave. Better way is to take a pencil and paper and draw a quick sketch. So here a wireframe i have drawn:

as you can see - the design consist of two columns: left one is product list and the right column - is the shopping cart itself.
  • Pressing on each one of product`s 'plus' button - will make the product appear inside shopping cart.
  • Each product instance at shopping cart has a "quantity" field where you can see how much units of this product is ordered, you can increase/decrease units number by pressing "up" or "down" arrows (you can as well press 'plus' button at some product at "product list" one more time to increase the units number)
  • If number of units is 0 - the product should no more appear in the shopping cart.

Starting to Code (Or, more correctly - where i start to coding)

For this post i will not use any traditional IDE like webstorm or vscode. Instead i will use online stackblitz editor.
Why? you may ask

  • Because you dont need to download & install anything on your machine
  • Because you dont need to wait until dependencies installed(at least at my comp the installing deps is more more slower then in stackblitz)
  • Because the future is to have all you need online (and we want to be a future guys, are we?)
  • Because it is how i will place a running demo in this post
Anougth reasons?

Start coding already!!!

Ok, lets start a new angular Project.

Now you have an Angular8 project in less than a second. Pretty fast, right?
(Try to do it using ng new my-project and see how much time is takes...)
Here we have already a "hello" component, lets rename it to ProductListComponent
Remember to Modify the code of app.module.ts file accordingly:

import { AppComponent } from './app.component';
// replace "hello"
import { ProductListComponent } from './product-list.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, ProductListComponent/*also here*/ ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Lets now go to ProductList component code and do some modifications:
1. rename the "name" input by "products"
2. change "selector" property to "product-list"
3. change markup at app.component.html to use "product-list" instead of "hello"

import { Component, Input } from '@angular/core';
@Component({
  selector: 'product-list',
  template: `
  <h1>Products List</h1>
  <div *ngFor="let product of products">{{product.name}}<div>
  `,
  styles: [`:host{border: 1px solid #000;}`]
})
export class ProductListComponent  {
  @Input() products: any[];
}

Now go to app.component.ts and lets create two public properties:
lists: productList and cartPorductList:


export class AppComponent  {
 productList = [
   {name: 'Z900', price: 8799},
   {name: 'shubert helmet', price: 999},
   {name: 'sport gloves', price: 99}
  ];
 cartProductList = [];
}

Low lets bind our newly baked ProductListComponent to show the products (at app.component.html):

 <product-list [products]="productList"></product-list>

by now the "output" screen of stackblitz editor (which you dont have in any not-online IDEs) should look like this:

Shopping Cart

In a same way we have created "PorductList" component - we will create now a "ShoppingCart" component. Just copy the "product-list.component.ts" and modify it accordingly:


@Component({
  selector: 'shopping-cart',
  template: `
   <h1>Shopping Cart</h1>
  <div *ngFor="let product of products">{{product.name}}<div>
  `,
  styles: [`:host{border: 1px solid #000;}`]
})
export class ShoppingCartComponent  {
  @Input() products: any[];
}

Note, the code is almost the same, the same "products" input, only names changed...
(Dont forget to register this component at app.module file too!)

Side By Side

Now we should make both - ShoppingCart and ProductList components to located side by side at parent (AppComponent) template.
There is a lot of various ways to implement this layout, and i will choose what i consider a most advanced and convenient way - the css-grid of CSS3 layout system:
Just place the following css code in app.component.css file and you done:


:host {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-column-gap: 10px;
}

You not have to add anything to child component styles and layout should look now like this:
TADAM!!!
If you new to grid-css feel free to read more here about grid-css techniques

Product Component

We may place the name price and "+" button at ProductList component template as well, but, i think - it will be more readble to place the markup and the logic into its own encapsulated component - the ProductComponent.
Lets create and register it again the same way we did with previous two components:


import { Component, Input } from '@angular/core';

@Component({
  selector: 'product',
  template: `
  <div>{{product.name}}/<div><button>+</button>
  <div>{{product.price}}/<div>
  `,
  styles: [`:host{border: 1px solid blue;}]`]
})
export class ProductComponent  {
  @Input() product: any;
}
// also lets modify the template of parent "ProductList" to use "product"
 <poduct *ngFor="let product of products" [product]="product">
 </product>
Now, remember the nice sketch i have show you at the begining?(i guess - you remember...)
Now look at the output...
What a mess!!!
But, lets use the same grid-css trick here! (just copy from app.component.css, paste to product.component.ts at "styles" section) and change the second "1fr" to "auto":

styles:[`
:host {
  display: grid;
  grid-template-columns: 1fr auto;// change the second "1fr" to "auto"
  grid-column-gap: 10px;
}
div:nth-child(1) {font-weight: bold;}
`]


And look: the things magically jumped right into their places!
Note that even "price" section moved to the bottom row because "1fr 1fr" means - the first 2 elements should caught all the available space at the row, and the next elements will be pushed to the next lower row, cool huh? css-grid rules!!!
One lust little thing:
Lets prettify the way the price displayed using cool "toLocaleString" es6 feature:

  <div>{{product.price.toLocaleString('en-US', {style: 'currency', currency: 'USD'})}}</div>
Now look at the improvements:
Much much better!

One way data flow

Lets talk a little bit about architecture. Currently our component structure is a tree, where "app" component uses as a root of the tree, its children is products and shopping cart and each of them should have its own children:

Currently the data is passed from parent to its children and grandchildren(as the red arrows show). Now the logic of '+' button should add products to "shoppingCartList" array which is property of its grandfather
(app component) - and i decided it will implement the same one-way data flow, only to the opposite direction(child -> parent -> grandparent).
We will use for this the Output & EventEmitter features of angular:
Lets add following code to product component

export class ProductComponent  {
  @Input() product: any;
  @Output() productAdded = new EventEmitter();
  addProductToCart(product) {
    this.productAdded.emit(product);
  }
}
// Also lets modify the template of product component by adding the clickHandler:
  <div>{{product.name}}</div><button (click)="addProductToCart(product)">+</button>
In the same way we need to add "addProductToCart" method, "productAdded" output and set its value with EventEmitter also to ProductList component (it will use now something like proxy between child Product and parent App components)

export class ProductListComponent  {
  @Input() products: any[];
  @Output() productAdded = new EventEmitter();
  addProductToCart(product) {
    this.productAdded.emit(product);
  }
}
// also update template:
  <product *ngFor="let product of products" [product]="product" (productAdded)="addProductToCart($event)"></product>
Now, the App component will be able to respond to "productAdded" event:
app.component.ts:

...
 addProductToCart(product) {
   this.cartProductList.push(product);
 }
// template:
<product-list (productAdded)="addProductToCart($event)" [products]="productList"></product-list>
We can see now products updated at ShoppingCart component:
We pretty close now to our final goal...

How about use Service?

Yes, it is good you asked. Actually, angular gives you ability to make data accessible to all level of components by using services. This is alternative architectural approach, and each one has its advantages and disadvantages.
One of advantages of one-way-flow is - that is very clear who triggers the change detection (a mechanism which responses to data changes), Also - if we would use services - how would i blabber about one-way-flow to you?

Good exmple for usage of "reduce" array method

Shopping Cart list is different from a product list, because same product may be added multiple times, but it should be displayed only once, and display the quantity of items (times '+' button clicked)
Thus: we must change a logic of "addProductToCard" method of AppComponent:
Istead just pushing product to "shoppingCartList" we will push it only if product NOT exists there yet
If product already exsit we will update "num" field of this product:


 addProductToCart(product) {
   const productExistInCart = this.cartProductList.find(({name}) => name === product.name); // find product by name
   if (!productExistInCart) {
     this.cartProductList.push({...product, num:1}); // enhance "porduct" opject with "num" property
     return;
   }
   productExistInCart.num += 1;
 }
but now we must change the ShoppingChart component header, so it will correctly display the total products number of order. For this we will use "reduce" method of array:

<h1>Shopping Cart ({{total()}})</h1>
// code
export class ShoppingCartComponent  {
  @Input() products: any[];
  total() {
    return this.products.reduce((acc, prod) => acc+= prod.num ,0)
  }
}

CartProduct Component

Lets quickly create the cartPorductComponent - it is almost similar to productComponent in its basics (its has 'product' Input too).


export class CartProductComponent  {
  @Input() product: any;
}
The main difference here is "quantity" input. Here is there the interesting things begin.
First: lets bind it to 'num' property of 'cartProduct' object, we will use angular [(ngModel)] directive

   <div *ngIf="product">
     <div>{{product.name}}</div>
     <input type="number" [(ngModel)]="product.num" min="0"/>
   </div>
Lets try to add some product from the list and see what we get:
Click the "Up" and "down" buttons and see that "total" quantity get updated
Very close to finish.
Now for the last step:
What should happen when quantity is reduced to zero?
Right, product should removed from "cart".
Lets add "ngModelChange" directive to "quantity" input :

<input type="number" [(ngModel)]="product.num" min="0" (ngModelChange)="modelChanged($event)"/>
and "modelChanged" handler at cart-product component

  modelChanged($event) {
    if (this.product.num === 0) {
      this.removeFromCart.emit(this.product)
    }
  }
Because of "one-way-data-flow" architecture we using here, we must update parent components as well:
shopping-cart.compontnet:

//template:
(productRemoved)="removeProduct($event)"
//code:
  @Input() products: any[];
  @Output() productRemoved = new EventEmitter();
  calcTotal() {
    return this.products.reduce((acc, prod) => acc+= prod.num ,0)
  }
  removeProduct(product) {
    this.productRemoved.emit(product)
  }
 
And finally, at app.component - the remove-from-cart logic:

  removeProduct(product) {
   this.cartProductList = this.cartProductList.filter(({name}) => name !== product.name)
  }
Now when reducing product quantity to 0 makes product to be removed from the cart.

Full Code

12/31/19

Building MonthPicker With React Hooks - Part 3

Reminder

Hi guys, thanks for following my blog. This post is third part of: "Building monthpicker using nothing but react hooks" series. It is better for you to have a look on previous two parts (if you didnt do it before)

Year navigation

Now for final functionalities - like navigating between years in dropdown header


   ... 
   const [year, setYear] = useState((new Date()).getFullYear());

   const incYear = e => {
      e.preventDefault();
      setYear(year + 1);
   }

   const decYear = e => {
      e.preventDefault();
      setYear(year - 1);
   }

   ...
Pressing the two ">" shaped buttons at dropdown header - will move you to prevous or next year.

One last thing - (without it the target cannot consider accomplished) is "monthClick" hadler. the month should change when some of "months" clicked. This could be easily achieved by attaching proper handler to each button:

   const monthClick = (e, idx) => {
      const currmonth = `0${idx+1}`.slice(-2);
      onChange(`${currmonth}.${year}`);
      toggleMenu();
   }
That it, you can view this codesandbox to see the whole code:

12/26/19

Building MonthPicker With React Hooks - Part 2

Outside Click Behavior

It is common feature for a menus - to be closed when user clicks somewhere else (outside the dropdown panel). To achileve this functionality - we can use this custom hook


import { useEffect } from "react";

function UseOuterClickNotifier(onOuterClick, innerRef) {
    useEffect(
      () => {
        // only add listener, if the element exists
        if (innerRef.current) {
          document.addEventListener("click", handleClick);
        }
  
        // unmount previous first in case inputs have changed
        return () => document.removeEventListener("click", handleClick);
  
        function handleClick(e) {
          innerRef.current && !innerRef.current.contains(e.target) && onOuterClick(e);
        }
      },
      [onOuterClick, innerRef] // invoke again, if inputs have changed
    );
}

export default UseOuterClickNotifier;

So now , our month menu opens when clickinh inside input and closes when clicking outside

   UseOuterClickNotifier(
      e => setShown(false),
      elRef
   );

Displaying Months

Now - to the main purpose of the our widget: the displaying months:


   const months = ['Jan', 'Feb', 'Mar', 'Spr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
   ...

   {shown && <div className="month-menu-dropdown">
     <header>
      <div className="top-arrow"></div>
      <button onClick={decYear}>></button>
      <div className="year-holder">{year}</div>
      <button onClick={incYear}><</button>
    </header>
     {months.map((month, index) => (<button key={month} onClick={e => monthClick(e, index)}>{month}</button>))}
    </div>}

to get the buttons ordered at 3 columns and 4 rows, i will use grid-css feature:

.month-menu-dropdown {
    position: absolute;
    right: 0;
    top: 59px;
    min-width: 170px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    column-gap: 2px;
    row-gap: 5px;
    z-index: 3;
    background: #fff;
    border: 1px solid var(--text-color);
    border-radius: 2px;
    border: 1px solid grey;
    padding: 5px 0;
}

12/23/19

Building MonthPicker With React Hooks - Part 1

Motivation

I thought it can be interesting to make a post about - how i build a "month picker" util, by myself, using my little css/html/react knowledge and nothing else.
Searching through the web - i stumble upon this implementation of month picker, but after looking more deeply into the code i asked myself - is there some way to implement this functionality little more simplier-for-user?

Design

First step - lets think about how this monthpicker should look and how it should act.
Here is screencast of monthpicker in action:

Popup Menu

First thing to start with - i thought about "popup menu" - a dropdown menu which pops when user clicks the input


import React, {useState, useRef} from 'react';
const MonthPicker = () => {
   const [shown, setShown] = useState(false); 
   const elRef = useRef(null);
   const toggleMenu = () => {
      setShown(!shown);
   }

   return (
      <span className="month-menu-holder" ref={elRef}>
         
         <input onFocus={toggleMenu}/>
        
         {shown && <div className="month-menu-dropdown">
            <header>
               <div className="top-arrow"></div>
               <button><</button>
               <div className="year-holder">{'2019'}</div>
               <button>></button>
            </header>
            {/* here will come a days buttons */}
         </div>}
      </span>
   );
}

Currently - the "Thing" we created - just know how to make the drop menu to appear, but - that is a good start. Of course - most of the "tricks" of invisibility and positioning done by proper css:

.month-menu-holder {
    position: relative;
    display: inline-block;
}

.month-menu-dropdown {
    position: absolute;
    right: 0;
    top: 59px;
    min-width: 170px;
    ...
}


12/18/19

Interesting Code Adventure With Compare the Array Of Objects

Recently i had some interesting task: The form i was working on - was supposed to update array of objects:


[
 {id: 1, framework: 'React'},
 {id: 2, framework: 'Angular'},
 {id: 3, framework: 'Vue'},
]

The problem was - the api has a support only for only one object at time and according to design - a form was planned to have only one "save" button (which suppose to trigger a batch saving)

 POST - api/framework
 DELETE - api/framework/:id
 UPDATE -api/framework/:id

So i needed to find a way to compare the two arrays - the original and the modified, and store the changes - in order to send a proper request for each one.

I will post Solution i finally came with

Firstly i decided to compare the strings of strigified arrays:


    const isIdentical = JSON.stringify(modifiedArr) === JSON.stringify(oldArr);
    if (isIdentical) {
      alert(`no changes`);
      return;
    }

Since - if arrays identical - there is no need to perform any request...

Removed

Next step i decided to collect removed array items (if were any):


const removed = oldArr.filter(({id}) => !modifiedArr.find(item => id === item.id));

Im only checking which items i cannot find in modified array.

Added

Collect the new items:


const added = modifiedArr.filter(({id}) => !oldArr.find(item => id === item.id));

Here im checking exactly the opposite - which items i cannot find in the old array

Modified

Collect the modified items


const modified = modifiedArr.filter(modifiedItem => !oldArr.find(item => JSON.stringify(modifiedItem) === JSON.stringify(item)))

Here im checking which items are different from old Array by checking their json strings.
Note: the in all the cases - i taking advantage of filter function of an Array.

12/15/19

What is Session Authentication?

Intro

I want to post here some post for a simpletons like me, who sometimes discovers basic things about web they didn`t knew. For example - recently i asked myself: "what is exactly session?" and, shame on me - i discovered that i cannot give quick and clear answer. So i publishing here some facts i came upon while searching across the web:

Session

Some data stored at server (variable) which connected to some specific user, and "lives" when this user is connected to server. The old classic way to implement this behavior - by creating a cookie.
cookie - some piece of data that comes from server and stored at browser, it has it unique "id" given by server, and may have some other data (like expiration time). cookie should be sent at headers of each request. Server will check the cookie (or if it present) and this way server will now about user and if he is connected

Implementing Session Authentication using Express

Since express.js is the only server framework i feel comfortable with - i will do all the demonstrations using this framework.
So here is some simple server with '/login' and '/private' apis:


const express = require('express');
const app = express();
const port = 4000;
/* must use cors module for recieve requests from different domains */
app.use(require('cors')())

app.post('/login', (req, res) => res.send({user: 'Lukas'}));

app.get('/private', (req, res) => res.send({products: [{name: 'ZX10R'}]}));

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Pretty nice & simple, right?

Accessing Api`s from client

We have created a grate piece of software in previous step, but - what worth a server if nobody uses it?
In other words: lets create some client which will consume the our shiny apis!


async function bla() {

    const data = await fetch('http://localhost:4000/login', {
      method: 'POST',
      headers: {'content-type': 'application/json'}
    }).then(data => data.json())

    console.log(`hi ${data.user}!`);
    // passed login lets show some private stuff!
    const productsData = await fetch('http://localhost:4000/private', {
      method: 'GET',
      headers: {'content-type': 'application/json'}
    }).then(data => data.json())
          
   console.log(`product: ${productsData.products[0].name}`)
 
}
bla();

As you can see(if you copied the code correctly) - the data being fetched:

Restricting Private Api`s using session

Currently the '/private' api can accessed by everybody (and it is suppose to be private!), so lets make it accessible only to one who passed the login request:
We will do it using cookie-session npm package.
0. install 'cookie-session' lib (npm i cookie-session)
1. use basic configuration:


const cookieSession = require('cookie-session')
app.use(cookieSession({
    name: 'mysession',
    secret: 'your-secret',
    maxAge: 30 * 60 * 1000 // 1/2 hour
}));

2. we will add some data to our session once user passed login request (this code mimics fetching user details from DB)

app.post('/login', (req, res) => {
    req.session.user = 'Lukas';
    res.send({user: 'Lukas'});
});

3. add some middleware which will block (return 401 response) for someone who tried to access to any(except '/login') api when unauthenticated

app.use((req, res, next) => {
    if (req.url.includes('login')) {
        next();
        return; 
    }

    if (!req.session || !req.session.user) {
        res.clearCookie('mysession');
        res.status(401).send({error: 'unauthorized'});
        res.end();   
    }
});

One more thing! We need modify now also the client code:

async function bla() {
    const productsData = await fetch('http://localhost:4000/private', {
      method: 'GET',
      credentilas: 'include', /* each request should carry the cookie at its headers */
      headers: {'content-type': 'application/json'}
    }).then(data => data.json())
          
   console.log(`product: ${productsData.products[0].name}`)
}
bla();

Also at cors configuration - we need to specify "origin" to be trusted:

app.use(cors({
  origin: 'http://localhost:3000', /* host where you client runs */
  credentials: true,
}));

Now, open the "network" panel of chrome dev tools. You should should see the following:

Tada!!! you just make a client to talk to server using session !!!

8/17/19

Deboundce In The Javascript

Intro

I decided to wrote here all the things i know about the "debounce" termin
So: by saying "debounce" people mean - some functionality that blocks multiple event handlers from trigger until some specified time interval (like one second) passed.

Example: scroller, that fires lots of "scroll" events when user scrolling down, should respond only to last scroll event within second (specified time interval) and ignore all the rest of events within that second.

Implementation

The key thing for implementing debounce - is to know about "clearTimeout" method, which cancels the previously scheduled actions:


let timer = null;
const debounce = (fn, delay) => {
  // clean previously scheduled actions
  clearTimeout(timer);
  // scheduled  the last action
  timer = setTimeout(fn, delay);
};

document
  .querySelector("#myInput")
  .addEventListener("input", e =>
    debounce(_ => console.log(e.target.value), 1000)
  );
// you will see only last event appears after the delay

Or, if you want to store "timer" inside the function without polutting global scope:


var debounce = (fn, time, immediate) => {
  let timeout;
  return (...rest) => {
    const [args] = rest;

    const later = () => {
      if (!immediate) {
        timeout = null;
        fn(args);
      }
    };

    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, time);

    if (callNow) {
      fn(args);
    }
  };
};
…

document
  .getElementById("app")
  .addEventListener("input", debounce(handle, 1000));

function handle(e) {
  console.log(e.target.value);
}


8/6/19

Why Do You Need "Set" In Javascript

Lets start with explanation what is set.
In the old times the only way to store some data list was by using array:

const users = ['Moshe','Vasia'];


These days some new players entering the scene:
The Set
It has "add", "delete", "clear" (for remove all the entries) methods

const users = new Set(['Moshe', 'Vasia']);
users.add('Ivan'); // will add one more entry

It also has "has" method for checking if item exists in Set:

console.log(users.has('Ivan')); // will print true

As far as I can see - the most cool feature (and may be a purpose of Set`s creation) - is uniqness: Set will not allow duplicates:

console.log(new Set([1,2,4,3,1])); // will 1,2,4,3

BUT (there must be always a "but")
all those cool features will not help you with following structure: (if the array consist of objects)

const users = new Set([
  {id:'123', name: 'Moshe'},
  {id:'124', name: 'Vasia'},
])

You will not be able to check if somebody with id '123' exist in Set using "has" method:

console.log(users.has('123')); // will be false

Also: it appears that Set not has a support for accessing entries by index And if you want to access first entry you will need to use something like this:

const user = users.values().next().value;
console.log(user); // will print "{id:123, name: 'Moshe'}"

Disappointing!
So, when this "Set" might be needed? you may ask...
The answer I found so far - is following scenario:
Remove duplicates:

const users = [
   {id:123, name: 'Moshe'},
   {id:124, name:'Vasia'},
   {id:125, name:'Ivan'},
   {id:123, name: 'Moshe'}// same Moshe one more time
];
const dedupedIds = Array.from(new Set(users.map(({id}) => id)))
console.log(dedupedIds); // will print 123,124,125

Conclusion

Although Set looks cool and promising - it seems there is not a much cases to use it (As far as I can see now)

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...