Wednesday 24 November 2021

Automatically Unsubscribe in Angular Component


let isFunction = fn => typeof fn === "function";

const doUnsubscribe = subscription => {
subscription &&
isFunction(subscription.unsubscribe) &&
subscription.unsubscribe();
};

const doUnsubscribeIfArray = subscriptionsArray => {
Array.isArray(subscriptionsArray) &&
subscriptionsArray.forEach(doUnsubscribe);
};

export function AutoUnsubscribe({
blackList = [],
arrayName = "",
event = "ngOnDestroy"
} = {}) {
return function(constructor: Function) {
const original = constructor.prototype[event];

if (!isFunction(original)) {
throw new Error(
`${
constructor.name
} is using @AutoUnsubscribe but does not implement ${event}`
);
}

constructor.prototype[event] = function() {
isFunction(original) && original.apply(this, arguments);
if (arrayName) {
doUnsubscribeIfArray(this[arrayName]);
return;
}
for (let propName in this) {
if (blackList.includes(propName)) continue;
const property = this[propName];
doUnsubscribe(property);
}
};
};
} 

//@AutoUnsubscribe() // use if direct property
@AutoUnsubscribe({ // use if you have array of subscriptions
arrayName:"subscriptions"
})
@Component({
selector: 'inbox'
})
export class InboxComponent {
one: Subscription;
two: Subscription;
subscription: [];
constructor( private store: Store<any>, private element : ElementRef ) {}

ngOnInit() {
this.one = store.select("data").subscribe(data => // do something);
this.two = Observable.interval.subscribe(data => // do something);

// this.subscriptions = [
// onResizeSubscription,
// deploymentSubscription,
// patientIdSubscription,
// createQuestionnaireLoadedSubscription,
// errorCreateQeustionnaireSubscription,
// ];
}

// This method must be present, even if empty.
ngOnDestroy() {
// We'll throw an error if it doesn't
}
}

Sunday 21 November 2021

Are observables synchronous or asynchronous?

 1.Synchronous observable:


Observables are lazy Push collections of multiple values.

In our async operator we've used setTimeout, this setTimeout will assure that the main thread will not get blocked because setTimeout
is a browser API and our code will be moved to the event loop.

const simpleBlockingOperator =
(noOfLoops: number) =>
<T>(source: Observable<T>): Observable<T> => {
return new Observable((observable) => {
source.subscribe({
next: (no) => {
let loops = 0;
while (loops !== noOfLoops) {
loops++;
}
console.log("Done loooping" + loops, " ", noOfLoops);
return observable.next(no);
},
error: (error) => observable.error(error),
complete: () => observable.complete(),
});
});
};
2.Asynchronous observable:

const simpleNonBlockingOperator =
(noOfLoops: number) =>
<T>(source: Observable<T>): Observable<T> => {
return new Observable((observable) => {
source.subscribe({
next: (no) => {
setTimeout(() => {
let loops = 0;
while (loops !== noOfLoops) {
loops++;
}
console.log("Done loooping" + loops, " ", noOfLoops);
return observable.next(no);
}, 0);
},
error: (error) => observable.error(error),
complete: () => observable.complete(),
});
});
};



Sunday 14 November 2021

Cut-Paste or Copy-Paste not working on Ubuntu 20.04 on using right-click context menu

 


set ubuntu new drive permissions 


Cut-Paste or Copy-Paste not working on Ubuntu 20.04 on using right-click context menu ?


sudo chown -v $USER:$USER /media/hp/e7582b74-0571-4a0d-b36f-e1ec8cb67c6f






Sunday 11 July 2021

rxjs takeUntil and takeWhile Example


https://stackblitz.com/edit/rxjs-pranay-example?file=index.ts


takeUntil

My favorite way of unsubscribing from streams is takeUntil. This operator will allow you to unsubscribe a stream when the stream passed as input to the operator emits an event. Oh, that seems too complicated, but it’s actually not.

Let’s see an example:

  • we have two observables that emit with an interval of respectively 1000 ms (1 second) and 100 ms
  • the stream that emits every 100ms will unsubscribe when the other stream emits, which will happen every 1 second



import { of, interval } from 'rxjs';
import { map, takeUntil, takeWhile } from 'rxjs/operators';

const source = of('World').pipe(map(x => `Hello ${x}!`));

source.subscribe(console.log);

//takeUntil
const slow$ = interval(1000); // emit every 100 ms

const fast$ = interval(100).pipe(takeUntil(slow$));

fast$.subscribe({
next(n) {
console.log(n);
},
complete() {
console.log('I am unsubscribed!');
}
});

slow$.subscribe();



takeWhile

This operator is very useful to unsubscribe streams based on their own value. One of the ways I needed to use this operator is to stop certain timers once they reach a certain number of iterations. For instance, a countdown timer.

In the following example, I want to stop a timer once it iterates for 5 times. —

  • the takeWhile operator accepts a predicate function whose parameter is the current value of the stream
  • if the predicate is truthy, it will keep emitting values; if it’s falsy, then it will unsubscribe the stream


import { of, interval } from 'rxjs';
import { map, takeUntil, takeWhile } from 'rxjs/operators';

const source = of('World').pipe(map(x => `Hello ${x}!`));

source.subscribe(console.log);


// takeWhile
const stream$ = interval(1000).pipe(takeWhile(n => n < 5));

stream$.subscribe({
next(n) {
console.log(n);
},
complete() {
console.log('I am unsubscribed!');
}
});



What are Subjects?

Subject is both an observable and observer.

  1. Observer — it has the next, error, and complete methods.
  2. Observable — it has all the observable operators, and you can subscribe to him.

A subject can act as a bridge/proxy between the source observable and many observers, making it possible for multiple observers to share the same observable execution.

remember that a subject is also an observer, and what observers can do? They can listen to observables with the next()error() and complete() methods. 




Monday 5 July 2021

create margin and padding helpers class using scss

 


/*
This .scss loop will create "margin helpers" and "padding helpers" for use in your web projects.
It will generate several classes such as:
.m-r-10 which gives margin-right 10 pixels.
.m-r-15 gives MARGIN to the RIGHT 15 pixels.
.m-t-15 gives MARGIN to the TOP 15 pixels and so on.
.p-b-5 gives PADDING to the BOTTOM of 5 pixels
.p-l-40 gives PADDING to the LEFT of 40 pixels
The first letter is "m" or "p" for MARGIN or PADDING
Second letter is "t", "b", "l", or "r" for TOP, BOTTOM, LEFT, or RIGHT
Third letter is the number of spacing in pixels. Adjust the amounts
generated by editing the $spaceamounts variable below.
*/

$spaceamounts: (5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 75, 100);
// Adjust this to include the pixel amounts you need.
$sides: (top, bottom, left, right);
// Leave this variable alone

@each $space in $spaceamounts {
@each $side in $sides {
.m-#{str-slice($side, 0, 1)}-#{$space} {
margin-#{$side}: #{$space}px !important;
}
.p-#{str-slice($side, 0, 1)}-#{$space} {
padding-#{$side}: #{$space}px !important;
}
}
}


/*
RUN GULP to generate the classes. Now you can use these helpers to customize spacing on HTML elements.
*/

Friday 18 June 2021

What are the different types of binding available in Angular ?

Property Binding - binding is set in one direction from component's property to template. Property binding example.

<img [src]="ImageUrl">

Event Binding - It's used to bind any event. Event binding example.

<button (click)="onUpdate($event)">Save</button>

Two way binding - It's used for two-way binding. Two-way data binding example.

<input [(ngModel)]="name">

Attribute binding - It's used to set the value of attribute directly. Attribute binding example.

<button [attr.aria-label]="help">help</button>

Class binding - It's used to add or remove class names from class attribute. Class binding example.

 <span [class.specialClass]="isSpecialClass">Special class</span>

Style binding - It's used to add or remove the style from style attribute. Style binding example.

<button [style.color]="isSpecialClass ? 'blue' : 'black'">Click Me</button>


What is Angular DSL?

A domain-specific language (DSL) is a computer language specialized to a particular application domain. Angular has its own Domain Specific Language (DSL) which allows us to write Angular specific html-like syntax on top of normal html. It has its own compiler that compiles this syntax to html that the browser can understand. This DSL is defined in NgModules such as animations, forms, and routing and navigation.


Basically you will see 3 main syntax in Angular DSL.


(): Used for Output and DOM events.

[]: Used for Input and specific DOM element attributes.

*: Structural directives(*ngFor or *ngIf) will affect/change the DOM structure.

 

 

Wednesday 16 June 2021

Apply vs. Call vs. Bind javascript example


Apply vs Call vs Bind Examples


Call


var person1 = {firstName: 'pranay', lastName: 'soni'};
var person2 = {firstName: 'test_f', lastName: 'test_l'};

function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.call(person1, 'Hello'); // Hello pranay soni
say.call(person2, 'Hello'); // Hello test_f test_l

Apply


var person1 = {firstName: 'pranay', lastName: 'soni'};
var person2 = {firstName: 'test_f', lastName: 'test_l'};

function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.apply(person1, ['Hello']); // Hello pranay soni
say.apply(person2, ['Hello']); // Hello test_f test_l

Bind


var person1 = {firstName: 'pranay', lastName: 'soni'};
var person2 = {firstName: 'test_f', lastName: 'test_l'};

function say() {
console.log('Hello ' + this.firstName + ' ' + this.lastName);
}

var sayHelloPranay = say.bind(person1);
var sayHelloTest = say.bind(person2);

sayHelloPranay(); // Hello pranay soni
sayHelloTest(); // Hello test_f test_l


When To Use Each

Call and apply are pretty interchangeable.
Just decide whether its easier to send in an array or a
comma separated list of arguments.

I always remember which one is which by remembering that Call is for
comma (separated list) and Apply is for Array.

Bind is a bit different. It returns a new function.
Call and Apply execute the current function immediately.


for await of vs promise.all in javascript


let i = 1;
function somethingAsync(time) {
console.log("fired");
return delay(time).then(() => Promise.resolve(i++));
}
const items = [1000, 2000, 3000, 4000];

function delay(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}

(async () => {
console.time("first way");
const promises = await Promise.all(items.map((e) => somethingAsync(e)));
for (const res of promises) {
console.log(res);
}
console.timeEnd("first way");

i = 1; //reset counter
console.time("second way");
for await (const res of items.map((e) => somethingAsync(e))) {
// do some calculations
console.log(res);
}
console.timeEnd("second way");
})();

 

Sunday 16 May 2021

useReducer in React

const [state, dispatch] = useReducer(reducer, initialArg, init);

An alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method. (If you’re familiar with Redux, you already know how this works.)

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

Here’s the counter example from the useState section, rewritten to use a reducer: 



const initialState = { count: 0 };

function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error();
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</>
);
}



Specifying the initial state

There are two different ways to initialize useReducer state. You may choose either one depending on the use case. The simplest way is to pass the initial state as a second argument:


  const [state, dispatch] = useReducer(
    reducer,
    {count: initialCount}  );

Lazy initialization

You can also create the initial state lazily. To do this, you can pass an init function as the third argument. The initial state will be set to init(initialArg).

It lets you extract the logic for calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action:

function init(initialCount) {  return {count: initialCount};}
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    case 'reset':      return init(action.payload);    default:
      throw new Error();
  }
}

function Counter({initialCount}) {
  const [state, dispatch] = useReducer(reducer, initialCount, init);  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({type: 'reset', payload: initialCount})}>        Reset
      </button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

  • Using useMemo( ) -
    It is a React hook that is used for caching CPU-Expensive functions.
    Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.
    useMemo( ) hook can be used to cache such functions. By using useMemo( ), the CPU-Expensive function gets called only when it is needed.

  • Using React.PureComponent -
    It is a base component class that checks state and props of a component to know whether the component should be updated.
    Instead of using the simple React.Component, we can use React.PureComponent to reduce the re-renders of a component unnecessarily.

  • Maintaining State Colocation -
    This is a process of moving the state as close to where you need it as possible.
    Sometimes in React app, we have a lot of unnecessary states inside the parent component which makes the code less readable and harder to maintain. Not to forget, having many states inside a single component leads to unnecessary re-renders for the component.
    It is better to shift states which are less valuable to the parent component, to a separate component.

  • Lazy Loading -
    It is a technique used to reduce the load time of a React app. Lazy loading helps reduce the risk of web app performances to minimal.