Time in Javascript

Check Time, Lead time, Crease Time, Decrease Time

function checkTime(value) {
    let d = new Date(0).setHours(value.substr(0, 2), value.substr(3, 2));
    let e = new Date(d);
    return e;
}

function checkLead(lead) {
    let d = new Date(0);
    console.log(d);
    d.setMinutes(d.getMinutes() + lead);
    console.log(d)
}

function increaseTime(value, lead) {
    let d = new Date(0).setHours(value.substr(0, 2), value.substr(3, 2));
    let e = new Date(d);
    let f = e.setMinutes(e.getMinutes() + lead);
    let g = new Date(f)
    return g.toString().substr(16, 5);
}

function decreaseTime(value, lead) {
    let d = new Date(0).setHours(value.substr(0, 2), value.substr(3, 2));
    let e = new Date(d);
    let f = e.setMinutes(e.getMinutes() - lead);
    let g = new Date(f)
    return g.toString().substr(16, 5);
}

Update and Delete ngRx

shopping-list.actions.ts

export const UPDATE_INGREDIENT = 'UPDATE_INGREDIENT';
export const DELETE_INGREDIENT = 'DELETE_INGREDIENT';

export class UpdateIngredient implements Action {
    readonly type = UPDATE_INGREDIENT;

    constructor(public payload: { index: number, ingredient: Ingredient }) { }
}

export class DeleteIngredient implements Action {
    readonly type = DELETE_INGREDIENT;

    constructor(public payload: number) { }
}

export type ShoppingListActions = AddIngredient | AddIngredients | UpdateIngredient | DeleteIngredient;

shopping-list.reducer.ts

export function shoppingListReducer(state = initalState, action: ShoppingListActions.ShoppingListActions) {
    switch (action.type) {
        case ShoppingListActions.UPDATE_INGREDIENT:
            const ingredient = state.ingredients[action.payload.index];
            const updatedIngredient = {
                ...ingredient,
                ...action.payload.ingredient
            }
            const ingredients = [...state.ingredients];
            ingredients[action.payload.index] = updatedIngredient
            return {
                ...state,
                ingredient: ingredients
            };
        case ShoppingListActions.DELETE_INGREDIENT:
            const oldIngredients = [...state.ingredients];
            oldIngredients.splice(action.payload, 1);
            return {
                ...state,
                ingredients: oldIngredients
            }
        default:
            return state;
    }
}

shopping-edit.component.ts

  onSubmit(form: NgForm) {
    const value = form.value;
    const newIngredient = new Ingredient(value.name, value.amount);
    if (this.editMode) {
      this.slService.updateIngredient(this.editedItemIndex, newIngredient);
      this.store.dispatch(new ShoppingListActions.UpdateIngredient({ index: this.editedItemIndex, ingredient: newIngredient }))
    } else {
      this.store.dispatch(new ShoppingListActions.AddIngredient(newIngredient));
    }
    this.editMode = false;
    form.reset();
  }

  onDelete() {
    this.slService.deleteIngredient(this.editedItemIndex);
    this.store.dispatch(new ShoppingListActions.DeleteIngredient(this.editedItemIndex));
    this.onClear();
  }


Multiple Actions

shopping-list.actions.ts

import { Action } from '@ngrx/store';
import { Ingredient } from 'src/app/shared/ingredient.model';

export const ADD_INGREDIENT = 'ADD_INGREDIENT';
export const ADD_INGREDIENTS = 'ADD_INGREDIENTS';

export class AddIngredient implements Action {
    readonly type = ADD_INGREDIENT;

    constructor(public payload: Ingredient) { }
}

export class AddIngredients implements Action {
    readonly type = ADD_INGREDIENTS;

    constructor(public payload: Ingredient[]) { }
}

export type ShoppingListActions = AddIngredient | AddIngredients;

shopping-list.reducer.ts

export function shoppingListReducer(state = initalState, action: ShoppingListActions.AddIngredientShoppingListActions) {
    switch (action.type) {
        case ShoppingListActions.ADD_INGREDIENT:
            return {
                ...state,
                ingredients: [...state.ingredients, action.payload]
            };
        case ShoppingListActions.ADD_INGREDIENTS:
            return {
                ...state,
                ingredients: [...state.ingredients, ...action.payload]
            }
        default:
            return state;
    }
}

recipe.service.ts

import { Store } from '@ngrx/store';
import * as ShoppingListActions from '../shopping-list/store/shopping-list.actions';

  constructor(private slService: ShoppingListService, private store: Store<{ shoppingList: { ingredients: Ingredient[] } }>) { }

  addIngredientsToShoppingList(ingredients: Ingredient[]) {
    this.slService.addIngredients(ingredients);
    this.store.dispatch(new ShoppingListActions.AddIngredients(ingredients))
  }

Dispatching Action in NgRx

We will start with add item

shopping-edit.component.ts

import { Store } from '@ngrx/store';
import * as ShoppingListActions from '../store/shopping-list.actions'

export class ShoppingEditComponent implements OnInit, OnDestroy {
  constructor(private slService: ShoppingListService, private store: Store<{ shoppingList: { ingredients: Ingredient[] } }>) { }

  onSubmit(form: NgForm) {
    const value = form.value;
    const newIngredient = new Ingredient(value.name, value.amount);
    if (this.editMode) {
      this.slService.updateIngredient(this.editedItemIndex, newIngredient);
    } else {
      this.slService.addIngredient(newIngredient);
      this.store.dispatch(new ShoppingListActions.AddIngredient(newIngredient));
    }
    this.editMode = false;
    form.reset();
  }

}

shopping-list.actions.ts

import { Action } from '@ngrx/store';
import { Ingredient } from 'src/app/shared/ingredient.model';

export const ADD_INGREDIENT = 'ADD_INGREDIENT';

export class AddIngredient implements Action {
    readonly type = ADD_INGREDIENT;
    payload: Ingredient;
    constructor(public payload: Ingredient) { }
}

The item functionallity will be work same as before

Initialize ngrx (Reduxe)

Create a store folder into that create shopping-list.reducer and shopping-list.actions ts files.

shopping-list.actions.ts

import { Action } from '@ngrx/store';
import { Ingredient } from 'src/app/shared/ingredient.model';

export const ADD_INGREDIENT = 'ADD_INGREDIENT';

export class AddIngredient implements Action {
    readonly type = ADD_INGREDIENT;
    payload: Ingredient;
}

shopping-list.reducer.ts

import { Ingredient } from '../../shared/ingredient.model';
import * as ShoppingListActions from "./shopping-list.actions";

const initalState = {
    ingredients: [
        new Ingredient('Apples', 5),
        new Ingredient('Tomatoes', 10),
    ]
}
export function shoppingListReducer(state = initalState, action: ShoppingListActions.AddIngredient) {
    switch (action.type) {
        case ShoppingListActions.ADD_INGREDIENT:
            return {
                ...state,
                ingredients: [...state.ingredients, action.payload]
            }
        default:
            return state;
    }
}

Need to import in app.module.ts file now.

app.module.ts

import { StoreModule } from "@ngrx/store";
import { shoppingListReducer } from './shopping-list/store/shopping-list.reducer';

@NgModule({
  imports: [
    StoreModule.forRoot({ shoppingList: shoppingListReducer })
  ],
})
export class AppModule { }

Initialize is done now start with normal component

shopping-list.component.html

<a class="list-group-item" style="cursor: pointer" *ngFor="let ingredient of ingredients (ingredients | async).ingredients; let i = index" (click)="onEditItem(i)">
{{ ingredient.name }} ({{ ingredient.amount }})
</a>

shopping-list.component.ts

import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';

export class ShoppingListComponent implements OnInit, OnDestroy {
  ingredients: Observable<{ ingredients: Ingredient[] }>;

  constructor(
    private store: Store<{ shoppingList: { ingredients: Ingredient[] } }>
  ) { }

  ngOnInit() {
    this.ingredients = this.store.select('shoppingList');
    // this.ingredients = this.slService.getIngredients();
    // this.subscription = this.slService.ingredientsChanged.subscribe(
    //   (ingredients: Ingredient[]) => {
    //     this.ingredients = ingredients;
    //   }
    // );

  }

  ngOnDestroy() {
    // this.subscription.unsubscribe();
  }
}

You will see here your application is working same as before.

how to add class only in inner pages not homepage

app.component.ts

export class AppComponent implements OnInit {
  previousUrl: any;
  constructor(private render: Renderer2, private router: Router) {
    this.router.events.subscribe(
      (event) => {
        if (event instanceof NavigationStart) {
          //for current page name
          let currentUrlSlug = event.url.slice(1);
          let currentUrlSlug2 = 'fixed-inner';
          if (this.previousUrl) {
            console.log('hit');
            this.render.removeClass(document.body, currentUrlSlug2);
          }
          if (currentUrlSlug) {
            this.render.addClass(document.body, currentUrlSlug2);
          }
          this.previousUrl = currentUrlSlug;
        }
      }
    )
  }
}

Now this fixed-inner class always show only on inner pages

how to add and remove class in body with routing

App.component.ts

export class AppComponent implements OnInit {
  previousUrl: any;
  constructor(private render: Renderer2, private router: Router) {
    this.router.events.subscribe(
      (event) => {
        if (event instanceof NavigationStart) {
          //for current page name
          let currentUrlSlug = event.url.slice(1);
          if (this.previousUrl) {
            this.render.removeClass(document.body, this.previousUrl);
          }
          if (currentUrlSlug) {
            this.render.addClass(document.body, currentUrlSlug);
          }
          this.previousUrl = currentUrlSlug;
        }
      }
    )
  }

}

Find prime number with position in Javascript

function primeMover(n){
    var primes = [2];
    var x = 3;
    var count = 0;
    do{
        for(var y=2; y<x; y++){
            if(x%y===0){
                count++;
            }
        }
        if(count===0){
            primes.push(x);
            x++;
        }else{
            x++;
            count=0;
        }
    }
    while(primes.length<n);
    return primes[primes.length-1];
}
primeMover(n);    

check large number from right side in array in Javascript

Also add dynamic key into Object

var arr = [1,2,25,46,6]
var newArr = [];
for(var i=0; i<arr.length; i++){
	var myObj = {}
	if(arr[i] < arr[i+1]){
		myObj[arr[i]] = arr[i+1]
		newArr.push(myObj);
    } else {
		myObj[arr[i]] = -1
		newArr.push(myObj);
    }
}

var newArr = [];
for(var i=0; i<arr.length; i++){
	if(arr[i] < arr[i+1]){
		newArr.push({[arr[i]] : arr[i+1]});
    } else {
		newArr.push({[arr[i]] : -1});
    }
}

How to check array value into Object in Javascript

–JS

var myObj = {
	name: 'Pradeep',
	age: 28,
	state: 'delhi',
	address: [{room:'1bhk', type:'semi'}],
	address2: [{room:'2bhk', type:'none'}],
	address3: [{room:'3bhk', type:'full'}],
}
for(var i=0; i<Object.keys(myObj).length; i++){
	for(var x=0; x<myObj[Object.keys(myObj)[i]].length; x++){
		if(myObj[Object.keys(myObj)[i]][x].room == '1bhk'){
            console.log(myObj[Object.keys(myObj)[i]][x])
        }
    }
}