Wednesday, 7 November 2018

Interview Programs

// N number of people are standing in a circle and 1st have knife, he kill 2nd then
3rd have knife, he kill 4th and so on then who will safe last


var a = 100;
var arr = [];
for (i = 1i <= ai++) {
    arr.push(i);
}
var i = 1;
while (arr.length > 1) {
    if (i > arr.length)
        i = 1;
    else if (i == arr.length)
        i = 0;
     //console.log(i,"lll",arr[i]);
    arr.splice(i1)
    i = i + 1;
}
console.log(arr[0]);

//Given a number N. The task is to find the largest factor of that number which is a perfect square.
function isNumberPerfectSquare(num) {
i = 1;
square = i * i;
while (num > square) {
i++;
square = i * i;
}
if (num == square)
return true;
return false;
}


function largestPerfectSquare(num, reminder, diviser, factor) {
if (isNumberPerfectSquare(factor)) {
return factor;
}
else {
while (reminder > 0) {
diviser++;
reminder = num % diviser;
}
return largestPerfectSquare(num, 1, diviser, num / diviser)
}
}
console.log("Largest Perfect square of 420 is:", largestPerfectSquare(420, 1, 1, 420));

Tuesday, 24 April 2018

Sorting

1. Selection sort:

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list. The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right. This algorithm is not suitable for large data sets as its average and worst case complexities are of Ο(n2), where n is the number of items.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>Click the button to sort the array in ascending order.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;   

function myFunction() {//Bubble sort works by repeatedly swapping the adjecent  elements if they are in wrong order.
let len=points.length;
for(let i=0; i<len-1; i++){
        for(let j=0; j<len-i-1; j++){
        if(points[j+1]<points[j]){
            let temp=points[j];
                points[j]=points[j+1];
                points[j+1]=temp;
            }
          }
      }   
    //points.sort(function(a, b){return a - b});
    document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

For Edit You can Use below Link:-

https://jsfiddle.net/OmPrakashPandey/Lpw43xyt/



2. Bubble Sort

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items

We observe in algorithm that Bubble Sort compares each pair of array element unless the whole array is completely sorted in an ascending order. This may cause a few complexity issues like what if the array needs no more swapping as all the elements are already ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap has happened or not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it will come out of the loop.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>Click the button to sort the array in ascending order.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points; 

function myFunction() {//Bubble sort works by repeatedly swapping the adjecent  elements if they are in wrong order.
let len=points.length;
for(let i=0; i<len; i++){
        for(let j=0; j<len-i; j++){
        if(points[j+1]<points[j]){
            let temp=points[j];
                points[j]=points[j+1];
                points[j+1]=temp;
            }
          }
      }   
    //points.sort(function(a, b){return a - b});
    document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>




For Edit You can Use below Link:-

https://jsfiddle.net/OmPrakashPandey/cfgrt2of//



Wednesday, 14 March 2018

Create filter Pipe in Angular5

dfAngular Pipe:-

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's Array of object data into filterd Array order (ascending /descending).

Create pipe using cli

ng g pipe filter-data

write below code in filter-data.pipe.ts file


import { Pipe, PipeTransform } from '@angular/core';
import { retry } from 'rxjs/operator/retry';

@Pipe({
name: 'filterData'
})
export class FilterDataPipe implements PipeTransform {

transform(items: any[], f: any, key?: string, keyF?: string): any[] {
if (items && Array.isArray(items)) {
if (Array.isArray(f)) {
let allFilter = [];
if (keyF) f.forEach((obj) => { allFilter.push(obj[keyF]); });
else allFilter = f;

if (key) {
return items.filter((it) => {
return allFilter.includes(it[key])
});
}
else {
return items.filter((it) => {
return allFilter.includes(it)
})
}
}
else {
if (key) {
return items.filter((it) => {
return it[key] === f
});
}
else {
return items.filter((it) => {
return it === f
})
}
}
}
return [];
}
}

Write below code where you want to sort data(In component html)


  1. Filter in Array of string:- e.g. var arr=['om', 'prakash', 'pandey']
<div class="mdl-cell mdl-cell--4-col">
<mat-form-field class="mat-form-field-custom">
<input matInput placeholder="Search by Audit Name" [(ngModel)]="searchText">
<mat-icon matSuffix>search</mat-icon>
</mat-form-field>
</div>

<div class=" mdl-cell mdl-cell--3-col mdl-cell--8-col-tablet
mdl-cell--12-col-phone matrix-names"
*ngFor="let name of (arr | filterData : searchText)">{{ name }}
</div>
  1. Filter in Array Of Objects:-  e.g. var userList=[{name:'om'}, {name: 'prakash'} , {name: 'pandey'}]
<div class="mdl-cell mdl-cell--4-col">
<mat-form-field class="mat-form-field-custom">
<input matInput placeholder="Search by Audit Name" [(ngModel)]="searchText">
<mat-icon matSuffix>search</mat-icon>
</mat-form-field>
</div>

<div class=" mdl-cell mdl-cell--3-col mdl-cell--8-col-tablet
mdl-cell--12-col-phone matrix-names"
*ngFor="let user of (userList | filterData : searchText : 'name')">{{ user.name }}
</div>
  1. Filter in Array Of Objects:-  e.g. var userList=[{name:'om'}, {name: 'prakash'} , {name: 'pandey'}] and input filter is object then in last parameter define the KEY by which you want to search
  2. Filter in Array Of Objects:-  e.g. var userList=[{name:'om'}, {name: 'prakash'} , {name: 'pandey'}] and input filter is also an array of object(for multi select dropdown) then second parameter is an Array of Object andn last parameter defined the KEY by which you want to search........



Create Sorting Pipe in Angular5

Angular Pipe:-

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's Array of object data into sorting order(ascending/descending).

Create pipe using cli

ng g pipe order-by

write below code in order-by.pipe.ts file


import { Pipe, PipeTransform } from '@angular/core';
import { retry } from 'rxjs/operator/retry';

@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(items: any[], key?: string, order?: string, typeOf?: string): any[] {

if (items && Array.isArray(items)) {

let asc = (order != 'dsc') ? -1 : 1, c, d;//c,d update only value not reffrence
return items.sort(function (a, b) {
if (key)
c = a[key], d = b[key];
else
c = a, d = b;

if (typeOf === 'date') {
c = typeof (c) === 'string' ? new Date(c) : c;
d = typeof (d) === 'string' ? new Date(d) : d;
}
else if (typeOf === 'number') {
c = parseFloat(c);
d = parseFloat(d);
}
return (c > d) ? (asc * -1) : (c < d ? asc : 0);
});
}
return [];
}
}


Write below code where you want to sort data(In component html)


<div *ngFor="let detail of auditSiteData | orderBy:'audit_date':'asc':'date'">
{{detail.audit_date }}
</div>

Friday, 7 July 2017

Difference Between event.preventDefault(), event.stopPropagation() and return false

  1. event.preventDefault() – It stops the browsers default behaviour.
  2. event.stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.
  3. Stops callback execution and returns immediately when called.
Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Example:- It's tested on W3School

<div onclick='executeParent()'>
  <a href='https://www.w3schools.com' onclick='executeChild()'>Click here to visit w3schools.com</a>
</div>

<script>
  function executeChild() {
   //event.preventDefault();  
   // event.stopPropagation();// stop event bubbling
    event.currentTarget.innerHTML = 'Click event prevented'
    alert('Link Clicked');
    if(event.currentTarget.innerHTML==='Click event prevented'){
    event.preventDefault(); // stop default behaviour of browser means href won't be call
    }
    //return false// it is used for exit from function/ callback at any where
  }

  function executeParent() {
    alert('Div Clicked');
  }
</script>

Wednesday, 14 June 2017

OOPs in JavaScript

JavaScript supports Object Oriented Programming but not in the same way as other OOP languages(c++, PHP, Java, etc.) do. The main difference between JavaScript and the other languages is that there are no Classes in JavaScript whereas Classes are very important for creating objects. However, there are ways through which we can simulate the Class concept in JavaScript.
Another important difference is Data Hiding. There is no access specifier like (public, private and protected) in JavaScript but we can simulate the concept using the variable scope in functions.

Object Oriented Programming Concepts

1) Object
2) Class
3) Constructor
4) Inheritance
5) Encapsulation
6) Abstraction
7) Polymorphism

Preparing the workspace

Create a new file "oops.html" and write this code on it. We will write all our JavaScript code on this file.
<html>
  <head>
    <title>JavaScript Object Oriented Programming(OOPs) Tutorial
    </title>
  </head>
  <body>
    <script type="text/javascript">
      //Write your code here.....
    </script>
  </body>
</html>

1) Object

Any real time entity is considered as an Object. Every Object will have some properties and functions. For example, consider a person as an object, then he will have properties like name, age, etc., and functions such as walk, talk, eat, think, etc. now let us see how to create objects in JavaScript. As mentioned previously there are so many ways to create objects in JavaScript like:
//1)Creating Object through literal
var obj = {};
//2)Creating with Object.create
var obj = Object.create(null);
//3)Creating using new keyword
function Person() {}
var obj = new Person();
We can use any of the above ways to create Object.

2) Class

As I said earlier there are no classes in JavaScript as it is Prototype based language. But we can simulate the class concept using JavaScript functions.
function Person() {
    //Properties
    this.name = "aravind";
    this.age = "23";
    //functions
    this.sayHi = function() {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p = new Person();
alert(p.sayHi());

3) Constructor

Actually, Constructor is a concept that comes under Classes. The constructor is used to assign values to the properties of the Class while creating an object using the new operator. In above code we have used name and age as properties for Person class, now we will assign values while creating new objects for Person class as below.
function Person(name, age) {
    //Assigning values through constructor
    this.name = name;
    this.age = age;
    //functions
    this.sayHi = function() {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p = new Person("aravind", 23);
alert(p.sayHi());
//Creating Second person instance
var p = new Person("jon", 23);
alert(p.sayHi());

4) Inheritance

Inheritance is a process of getting the properties and function of one class to other class. For example, let’s consider "Student" Class, here the Student also has the properties of name and age which have been used in Person class. So it's much better to acquiring the properties of the Person instead of re-creating the properties. Now let’s see how we can do the inheritance concept in JavaScript.
function Student() {}
//1)Prototype based Inhertance
Student.prototype = new Person();
//2)Inhertance throught Object.create
Student.prototype = Object.create(Person);
var stobj = new Student();
alert(stobj.sayHi());
We can do inheritance in above two ways.

5) Encapsulation

Before going on to Encapsulation and Abstraction first we need to know what Data Hiding is and how can we achieve it in JavaScript. Date hiding is protecting the data from accessing it outside the scope. For example, In Person class, we have Date of Birth (dob) properties which should be protected. Let's see how to do it.
function Person() {
    //this is private variable
    var dob = "8 June 2012";
    //public properties and functions
    return {
        age: "23",
        name: "aravind",
        getDob: function() {
            return dob;
        }
    }
}
var pobj = new Person();
//this will get undefined
//because it is private to Person
console.log(pobj.dob);
//Will get dob value we using public
//funtion to get private data
console.log(pobj.getDob());
Wrapping up of public and private data into a single data unit is called Encapsulation. The above example is the one that best suites Encapsulation.

6) Abstraction

Abstraction means hiding the inner implementation details and showing only outer details. To understand Abstraction we need to understand Abstract and Interface concepts from Java. But we don't have any direct Abstract or Interface in JS.
Ok! now in order to understand abstraction in JavaScript lets takes an example from JavaScript library Jquery. In Jquery we will use
$("#ele")
to select select an element with id ele on a web page. Actually this code calls negative JavaScript code
document.getElementById("ele");
But we don't need to know that we can happy use the $("#ele") without knowing the inner details of the implementation.

7) Polymorphism

The word Polymorphism in OOPs means having more than one form. In JavaScript an Object, Property, Method can have more than one form. Polymorphism is a very cool feature for dynamic binding or late binding.
function Person() {
    this.sayHI = function() {}
};
//This will create Student Class
function Student() {};
Student.prototype = new Person();
Student.prototype.sayHI = function(l) {
        return "Hi! I am a Student";
    }
    //This will create Teacher Object
function Teacher() {};
Teacher.prototype = new Person();
Teacher.prototype.sayHI = function() {
    return "Hi! I am a Teacher";
}
var sObj = new Student();
//This will check if the student
//object is instance of Person or not
//if not it won't execute our alert code.
if (sObj instanceof Person) {
    alert("Hurry! JavaScript supports OOps");
}

Conclusion

JavaScript supports Object Orientezd Programming(OOP)Concepts. But it may not be the direct way. We need to create some simulation for some concepts.
<html>
  <head>
    <title>JavaScript Object Oriented Programming(OOPs) Tutorial
    </title>
  </head>
  <body>
    <script type="text/javascript">
      //1)Creating Object through literal
var obj = {};
//2)Creating with Object.create
var obj = Object.create(null);
//3)Creating using new keyword
//function Person() {}
//var obj = new Person();

function Person1() {
    //Properties
    this.name = "aravind";
    this.age = "23";
    //functions
    this.sayHi = function () {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p1 = new Person1();
alert(p1.sayHi());



function Person(name, age) {
    //Assigning values through constructor
    this.name = name;
    this.age = age;
    //functions
    this.sayHi = function () {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p = new Person("aravind", 23);
alert(p.sayHi());
//Creating Second person instance
var p = new Person("jon", 23);
alert(p.sayHi());


function Student() { }
//1)Prototype based Inhertance
//Student.prototype = new Person("Om Prakash", 23);

//2)Inhertance throught Object.create
//Student.prototype = Object.create(new Person("Om", 23));

Student.prototype = function write(name) {
    alert(name);
}

var stobj = new Student();
console.log(stobj,"ok")
alert(stobj.Test("omdsfdgfhfg"));


function Person2() {
    //this is private variable
    var dob = "8 June 2012";
    //public properties and functions
    return {
        age: "23",
        name: "aravind",
        getDob: function () {
            return dob;
        }
    }
}
var pobj = new Person2();
//this will get undefined
//because it is private to Person
console.log(pobj.dob);
//Will get dob value we using public
//funtion to get private data
console.log(pobj.getDob());

    </script>
  </body>
</html>