Showing posts with label ES6. Show all posts
Showing posts with label ES6. Show all posts

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

7/6/19

Tagged Template Literals

Ok, everybody heard about "backticks" ES6 feature...


 const hero = 'Splinter'
 console.log(`My name is ${hero}`); 
// will print "My name is Splinter"

But recently I stumble upon following code I could not understand:

import { css, cx } from 'emotion'

const color = 'white'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
  >
    Hover to change color.
  </div>
)

What is this strange syntax?

Tagged Template Literals

Well it appears you can tag a template with function
Like this:

 const hero = 'Splinter';

 const printHero = html`My name is ${hero}`;
 // here is the function:
 function html(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += `${string} ${values[i] || ''}`;
   });
   return str;
 }

/*
printHero will print:
"My name is  <span class='hl'>Splinter</span> <span class='hl'></span>"
*/

Using tagged template gives you ability to control the way the template is parsed.

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

12/11/18

Distructuring cheatsheet

Since I keep find myself forgot the ES6 destructuring syntax again and again I decided to publish this cheatsheet:

If you want to print one property of object:


const object = {name:'vasia'};
const {name} = object; 
console.log(`${name}`); // vasia 


If you want to this property to be named differently (bio)


const object = {name:'vasia'};
const {name: bio} = object; 

console.log(`${bio}`); // vasia 


If this property is inside other property (person)


const object ={person: {name:'vasia'}};
const {person:{name}} = object;

console.log(`${name}`); // vasia 
Hope this post will make me remember...

7/27/18

The .every method i discovered today

Looking on react-redux example i found the following line:


  if (user && requiredFields.every(key => user.hasOwnProperty(key))) {
    console.log('no need to call "fetch"')
    return null
  }

Notice the usage of "every" statement.

Every

So, what is the advantage of "every"?
consider you have the following array:


const arr = [{name:'yoyo', active:true}, {name:'momo', active:true}, {name:'bobo', active:false}]

How can you quickly know if all users are active?
So, you can loop through the array with "forEach", like this

let everybodyIsActie = true;
arr.forEach(user => {
   if(!user.active) { // if even one is not active
     everybodyIsActie = false;
   }
})
if(everybodyIsActie) {
 console.log('everybody dance now!')
}

But, much more awesome is to use "every" statement:

if(arr.every(user => user.active)) {
 console.log('everybody dance now!')
}

No need to use any variables
Unlike "forEach" (which doesnt returns enything) "every" returns true if every array item fills the condition
See you in my next post!

11/17/16

Organizing Your Angularjs Typescript Project

In one of my previous posts i found how to compile typescript files to javascript and i was very happy with myself because of my success. Since then i had little more experience with typescript. And now i have a few more points to share:

Using Import In Your Typescript Project

I have noticed many angularjs and angular2 projects using Import syntax. That way they not need to compile each file separately, instead you can compile only main file while all other files included in it (like in less or sass)
For exapmle :
Instead put all the things in your JS app.js file


//OOOOOLD STUFF.. BLAHHH
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

In typescript, you can move the config logic to its own separate config.ts file:

 export function config($locationProvider: ng.ILocationProvider, $routeProvider: angular.route.IRouteProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.otherwise({redirectTo: '/view1'});
  };



and import it to app.ts main file:

/// 
import { config } from './config';///<--HERE
module angularSeed {
'use strict';

  // Declare app level module which depends on views, and components
  angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.version'
  ]).config(config)

}
 

Import Is ES6 Syntax (Not Typescript!)

So, if you need to transpile your code either from ES6 and from typescript - i cannot think about other tool than webpack.

Weeeebpaaaack....
Webpack supports ES6 natively and for get it to compile typescript you only need to include ts-loader:
 
var webpack = require('webpack');
var path = require('path');
module.exports = {
    context: path.join( __dirname, '/app'),
    entry: 'app.ts',
    output: {
        filename: 'app.js',
        path: path.join( __dirname, '/app')
    },
    resolve: {
        root: path.join( __dirname, '/app'),
        extensions: ['', '.ts', '.webpack.js', '.web.js', '.js']
    },
    module: {
        loaders: [//<-- TYPESCRIPT, COOOL
        // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.ts?$/, loader: 'ts-loader' }
        ]
    }
}

Of course you need to include this webpack.config.js file in your project And update package.json with too more entries:
 
    "typings": "^0.8.1",
    "webpack": "1.13.1",
 

Build The Project

Since we using webpack now for build the project, the command to compile will be:


node_modules/.bin/webpack
 

Hope you have fun reading...
Visit my cool REPO

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