Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

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)

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.

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)

7/16/19

3 Design Patterns With Javascript By Example

Hi readers. I decided to list here some 3 design patterns i knew (Or so i think) implemented with Javascript:

1. Observer

Lets start with Observer pattern:
the special thing about this pattern is that:
it keep tracking changes on some object, and if changes occurred - it broadcasts the changes the to dependent objects.

Subject

To implement the pattern in javascript we need firstly create a "subject":

let Subject = function() {
  let observers = [];
  return {
    subscribe(ob) {
      observers.push(ob)
    }
    unsubscribe(ob) {
      observers.splice(observers.indexOf(ob), 1)
    },
    notify(ob) {
      if(observers.indexOf(ob)===-1) {return;}
      observers[observers.indexOf(ob)].notify()
    }
  }
}

As you can see, subject must contain "subscribe", "unsubscribe", and "notify" methods and store all the "observers" at some inner storage/variable

Observers

Next thing - lets create the Observer object/class - the only thing it must have - is a "notify" method (for being notified)

let Observer = function(num){
 return { notify: () => console.log(`num ${num} notified`)}
}

Thats it - from now we can create observers, subscribe and notify to observers that subscribed:

let s = new Subject();
let ob1 = new Observer(1)
s.subscribe(ob1);
s.notify(ob1);
s.unsubscribe(ob1);
s.notify(ob1); // will not print, because it unsubscribed

The example of this pattern usage, is "addEventListener" method where we can subscribe to some browser events (like click)

2. Factory

This pattern lets users to create objects ONLY by using "creator" (not directly by using "new" keyword)


let CarCreator = function(modl) {
  switch(modl) {
    case "zaporojets":
     return new Zaporojets(); // only creator can use "new"
     break;
    case "volga":
     return new Volga(); // only creator can use "new"   
     break;
  }
 

The idea here to simplify the objects instantiation for users - they only need to supply the type of car as a string:

 let my= CarCreator("volga");


3. Singelton

The idea of this pattern is NOT to let creation of more than one instance of some object:
Here is one of the ways i can think of - not to let users to use "new" keyword:


var Singelton = (function(){
  function someObj() {
    return {
      name:'vasia'
    }
  }
  // only here you can use the 'new'
  return new someObj();
  
}())
console.log(Singelton.name);// will print "vasia"
console.log(new Singelton);// will cause error

The example of this pattern usage, can be the great old JQuery library - that allows you only to use their "$" object without any "new"s prior to it...

4/14/19

For the first time in my life - i dare to interview the interviewer

Recently I went to some job interview, which i, lets face the truth - totally failed. Since my career as developer last longer than 10 years, and had chance to work in a lot of places and on a lot of projects - it is definitely not my first interview, and event not first failed interview. Yet, at this post I want to tell you about some unique experiences I had during this particular adventure.

Details

Lets start from the beginning: It was an interview for the front-end position, and i was asked some javascript questions, like: how to check if a variable is an Array, or: how to prevent click event from bubbling from a child element to its parent. To be honest - I found myself caught unprepared for those questions (since almost year im working as a devops and completely forgot the differences between currentTarget and target, e.preventDefault and e.stopPropagation - shame on me!).
Yet the interesting thing was, that at some point, instead of focusing on my loose situation - I found myself trying to analyze the situation of the team that seeking to hire some frontend developer - and how it would be feel like working at this team

Conclusions

Here are some conclusions I come up with:

  • The interviewer didnt knew about ES Array.isArray method (instead - the answer he considered right was
    
    variableToCheck.constructor === Array
    
    
    )
  • Interviewer was surprised to find about existence of native javascript "fetch" method - instead he preferred to use jQuery ajax method for doing ajax request
  • The question about stopPropagation was a part of question:
    "how do you prevent a click on some element inside modal window to propagate to an overlay, when implementing modal dialog"
    - i tried to point out that nowadays browsers come up with a dialog HTML5 element which do exactly the dialog scenario (without need of coding anything) - but again caught the interviewer by surprise

Summary

Things can have various - a negative and a positive angles. At least I finally find out that as much important as to prepare yourself well for an interview - It is also important to try and figure out: what kind of work need to be done in the place you apply for. For example - this place did the impression of building some kind of new javascript framework instead of using some current, much better and simplier existing tools - a work I for sure would not be comfortable doing...

3/25/19

Implementing javascript Promise by myself

Motivation

I remember that once (at some job interview) i was asked to write the Promise implementation by myself. Since it was long ago, and i dont remember what i wrote then (or if) - I decided to take the challenge again.
So i will write here about the process of implementation step by step.

Class

First of all - i decided to take advantage of ES6 feature - the classes, which makes you to write classes instead of functions:


// using ES6 "class" feature
class MyPromise {
  constructor() {
    console.log('constructor called');
  }
}
const p = new MyPromise();

Executor

One of the most significant specifications of Promise - is that it must receive an "executor" as parameter
Executor must be passed by user and it must be function
I implemented it - by placing executor as a constructor parameter:


class MyPromise {
  constructor(executor) {
    executor();
  }
}
// must get executor fired 
const p = new MyPromise(()=>{
  console.log('executor fired')
});

Resolve and Reject

A Promise executor must have two parameters - resolve and reject.
These "resolve" and "reject" are promise methods which can be passed as parameters to function where user can inject them according to his needs


// passing "res" and "rej" memebers to executor
class MyPromise {
  constructor(executor) {
    executor(this.resolve, this.reject);
  }
  resolve() {
    console.log('resolve fired');
  }
  reject() {
    console.log('reject fired');
  }  
}
const p = new MyPromise((res, rej)=>{
  res(); // calling the resolve
});

Then

Until now it was pretty easy...
Now comes the hard part: the "then"
The Promise must return the "then" and "catch" methods in which user should be able to pass success and error callbacks
It is not difficult to get "then" method returned:


class MyPromise {
  constructor(executor) {
    executor(this.resolve, this.reject);
  }
  ...
  ...
  then() { // then added to "myPromise" object
 
  }
  catch(err)  {
    
  }
}

The goal here is to get "success" callback to fire if "resolve" method called inside the executor
Here where is had 2 difficulties:
- the success callback must be already set when resolve method called (since resolve must trigger it! )
- how to pass "this" into resolve, since it called from "outside"!
I manage to solve the first obstacle by using "setTimeout", to call the executor asyncronously

// then must be returned
class MyPromise {
  constructor(executor) {
    setTimeout(()=>{executor(() => this.resolve(), () => this.reject());});   
  }
  
  resolve() {
   this.success && this.success(); // this.success should be set before resolve called 
  }
  reject() {
    console.log('reject fired');
  }
  then(cb) {
    this.success = cb;
  }
  catch(err)  {
    
  }
}
const p = new MyPromise((res, rej) => {
  res();
});
p.then(() => {
   console.log(`then callback fired `);
})

Data of Resolve

The last specification i decided to implement - is make "resolve" to able pass data to "success"
Here is what i come with:


//  "res" should pass data
class MyPromise {
  constructor(executor) {
    setTimeout(()=>{executor((d) => this.resolve(d), () => this.reject());}); 
  }
  
  resolve(data) {
   this.success(data);
  }
  reject() {
    console.log('reject fired');
  }
  then(cb) {
    this.success = cb;
  }
  catch(err)  {
    
  }
}
const p = new MyPromise((res, rej) => {
  res('o'); // "o" is the example data
});
p.then((data) => {
   console.log(`then fired ${data}`);
})

Summary

The "creating my own Promise" challenge - made me to think about few interesting question I nave not thought until now
I'm not sure i did the best solution possible here, but now i have motivation to look and search for implementations of better javascript coders ...

2/8/19

Fetch the data using nested requests

Recently I was challenged with relatively common task - to fetch the data using nested requests.
More into the details:
the task was "to fetch GitHub users using GitHub API"(which s easy, but here is caveat:) each user must have a repoCount field (where total count of his owned repos should display):
The GitHub api ave the endpoint which brings you GitHub users, but each user has only "repos_url" field - a link to fetching repos

const token = 'your-github-access-token-here';

function getUsers(since=0) {
 const gitUri =`https://api.github.com`;
 const usersUri = `${gitUri}/users?per_page=10&since=${since}&access_token=${token}`;
 fetch(usersUri)
   .then(d => d.json())
   .then(data => {
      //  must get only those relevant two fields
      const modified_users = data.map(({login, repos_url}) => ({login, repos_url}));
      console.log(modified_users[0]);
   });
}

getUsers(0);
Outcome:
To bring the repos-count you will need to make one more request for each user to fill the missing data:

function getReposCount(repos_url) {
   // lets set "per_page" param to 10000
   // assuming no one can have so much repos
   // this way we will get the count using "length" property
   const reposUri = `${repos_url}?per_page=10000&access_token=${token}`;
   return fetch(reposUri)
   .then(d => d.json())
   .then(repos => {
     return repos.length || 0;
   })
}

Now we must change our "getUsers" so it will loop through all users and modify each user`s data properly:

 fetch(usersUri)
   .then(d => d.json())
   .then(data => {
      // loop through collection of users
      let promises = data.map(({login, repos_url}) => getReposCount(repos_url)
        .then(count => ({login, count}))); 
   
      Promise.all(promises).then((users) => {
         // lets display the data of ninth user
         console.log(users[9]); 
      })
   });

Now you can see the output:
The "count" field is added to user object!

3/20/18

Creating Javascript Router With Vanilla Javascript

What is router?
Router is a way to get different content in response to changes of url.
example:

That way it easy to memorize the url, and also you are able to navigate exact to product you need by the link (/vehicle/297 will lead you to SV650).
But what it means when speaking about JavaScript? Can JavaScript change the url without triggering full refresh of page?

Yes You Can

 It appears that javascript can change the url with HTML5 feature:

window.history.pushState("object or string", "sv650", "/sv650");



But How To Subscribe To Url Changes?

Yes, there is another HTML5 feature for it:
You can subscribe to 'pushstate' event:


window.addEventListener('popstate', (e) => {
  ...
});

Here is stackblitz project demonstrating routing in action

Summary

In this post you have learned that all 'Router' thing is actually very simple, and can be achieved with few pure javascript commands...
If you need more customizations like 'hash' Here is navigo vanilla javascript router...

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...