Shallow Copy and Deep Copy in Javascript: Simplest example
Shallow copy:
var a = {name:"john"};
var b = a;
console.log(b.name);
output: "john";
b.name = "Michael";
console.log(b.name);
output: "Michael";
console.log(a.name);
output: "Michael";
Deep copy:
var a = {name:"john"};
var b = JSON.parse(JSON.stringify(a));
console.log(b.name);
output: "john";
b.name = "Michael";
console.log(b.name);
output: "Michael";
console.log(a.name);
output: "john"
Implement Search in a listview in Angular JS - Simple example code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.search="";
$scope.data = [
{title:'Mumbai', language:'Marathi'},
{title:'Delhi', language:'Punjabi'},
{title:'Trivandrum', language:'Malyalam'},
{title: 'Kolkata', language:'Bengali'}
]
})
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="search" placeholder = "Search"/>
<div>
<ul>
<li ng-repeat="item in data" ng-if="data[$index].title.toUpperCase().indexOf(search.toUpperCase())>-1">{{item.title}}</li>
</ul>
</div>
</body>
</html>
Pass data from one controller to another controller using service in Angular JS / how to use Encapsulation in Angular JS / Setter-Getter concept in Angular JS
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.service('myservice', function () {
var Name;
/*Setter function*/
this.setName = function(name) {
this.Name = name;
}
/*Getter function*/
this.getName = function () {
return this.Name;
}
});
app.controller('firstcontroller', function($scope,myservice) {
$scope.myname = "developer";
/*Sets the value in first controller*/
myservice.setName($scope.myname);
});
app.controller('secondcontroller', function($scope,myservice) {
$scope.hit = function () {
/*Get the value in second Controller*/
alert(myservice.getName());
}
});
</script>
<body ng-app="myApp">
<div ng-controller="firstcontroller">
<P>This is first controller where you are using the setter function.</P>
</div>
<div ng-controller="secondcontroller">
<p>This button is in second Controller which uses the getter function.</p>
<input type = "button" value = "Hit Me" ng-click='hit();'/>
</div>
</body>
</html>
Stacked Bar Chart and Pie Chart / Implementation of Cross Filter / Dealing with non-numeric data in D3JS / many-to-many mapping in Cross Filter - DcJS
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<script type="text/javascript" src="d3.js"></script>
<script type="text/javascript" src="crossfilter.js"></script>
<script type="text/javascript" src="dc.js"></script>
<style>
#piediv {
float:left;
width:50%;
}
#stackbardiv {
float:right;
width:50%;
}
</style>
<script>
/* Dummy Data in the form of Array*/
var experiments = [
{ Region: "PhaseA", Status:"Error"},
{ Region: "PhaseB", Status:"Error"},
{ Region: "PhaseA", Status:"Warning"},
{ Region: "PhaseC", Status:"Warning"}];
function execute() {
/* Configurations for Pie Chart*/
var piechart = dc.pieChart("#piediv");
var ndx = crossfilter(experiments);
runDimensionPie = ndx.dimension(function(d) {return d.Status;})
speedSumGroupPie = runDimensionPie.group().reduceCount(function(d) {return d.Status});
piechart.width(400).height(400).dimension(runDimensionPie).group(speedSumGroupPie).legend(dc.legend());
/* Configurations for Stacked Bar Chart*/
var barchart = dc.barChart("#stackbardiv");
runDimensionBar = ndx.dimension(function(d) {return d.Region;});
speedSumGroupBar = runDimensionBar.group().reduceSum(function(d) {return d.Status=="Error"?1:0;});
speedSumStackBar = runDimensionBar.group().reduceSum(function(d) {return d.Status=="Warning"?1:0;});
barchart.dimension(runDimensionBar).group(speedSumGroupBar).x(d3.scale.ordinal()).xUnits(dc.units.ordinal).stack(speedSumStackBar);
dc.renderAll();
}
</script>
</head>
<body onload="execute();">
<h1 align = "center"> DC CHARTS </h1>
<div id ="piediv"></div>
<div id ="stackbardiv"></div>
</body>
</html>
MVC implementation using core Javascript : Simple Example
MVC stands for model view controller, it is often framed as a complex architecture but actually it is not. Model is just a data-model, it can be in any format; JSON, Array of objects, key-value pair, anything. View is simply the interface where user can watch the data and perform actions on it. Controller is a function under which data is processed and user actions are processed on data.
Below is the simple example of MVC, though it is one way in which data is processed and displayed to the user but it can really clear the concept of MVC in core Javascript.
<!doctype html>
<html>
<script>
/*Model*/
var arr = [{name:"Aditi"},{name:"Sumit"}];
/*Controller*/
var controller = (function() {
data = arr[0].name;
function processData() {
return this.data+" - Software Engineer";
};
return processData();
});
/*View*/
function renderView() {
var data = controller();
document.getElementById("mainview").innerHTML= data;
}
</script>
<body onload="renderView();">
<div id = "mainview"></div>
</body>
</html>
How to use Promise API in core javascript/Promise API simple example in javascript
JS waits for none! it is executed line by line but there are some situation where we want that particular piece of code should execute after certain asynchronous operation, like displaying an alert message after successfully receiving the response of the request sent to the server. Normally, JS wouldn't wait for the response and the alert code will be executed even before receiving the response from the server. So to solve this kind of situation we need a design where we can allow alert code to be executed after successfully receiving the response from the server. This architectural pattern is Promise.The name itself suggests that it will 'promise' you to get you the result of any asynchronous operation and it does!
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
![]() |
| Source: MDN |
Methods in Promise API:
Promise.all(iterable)
Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in the same order as defined in the iterable. If the returned promise rejects, it is rejected with the reason from the first promise in the iterable that rejected.
Promise.race(iterable)
Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.
Promise.reject(reason)
Returns a Promise object that is rejected with the given reason.
Promise.resolve(value)
Returns a Promise object that is resolved with the given value.
Creating a Promise:
function test() {
var mypromise = new Promise(function(resolve,reject){
//Do some asynchronous operation
resolve(result of asynchronous operation);
reject(reason of failure of asynchronous operation);
});
return mypromise;
}
Getting value from the Promise or perform further task after execution of asynchronous task written under promise:
test().then(function(result){
//perform further task
}).catch(function(reason){
//console the reason of failure
console.log(reason);
});
Simple example javascript Promise code
function test(num) {
var mypromise = new Promise(function(resolve,reject){
if(num<=5){
//Here we use setTimeout, in reality you would be using API calls.
setTimeout(function(){
resolve("the value is "+num);
},3000);
} else {
reject("input exceeds the limit");
}
});
return mypromise;
}
Usage:
test(4).then(function(result){
console.log(result);
}).catch(function(reason){
console.log(reason);
});
Encapsulation in Javascript/getter-setter in Javascript/POJO class in Javascript : simplest example
Encapsulation is an object oriented concept, however it can be used in core Javascript-ES5 using certain logic. Lets have a look on the below example:
Encapsulation is an object oriented concept, however it can be used in core Javascript-ES5 using certain logic. Lets have a look on the below example:
/*JS class*/
var details = (function(){
var _name; //private variable
var _age; //private variable
//inner function or closure set as 'public' using 'this' keyword
this.setDetails = function(name,age) {
_name = name;
_age = age;
}
//inner function or closure
this.getDetails = function() {
return _name+" is "+_age+" years old.";
}
});
var mydetails = new details(); //Creating object of the class 'details'.
mydetails.setDetails("John","24"); //Setting up details
mydetails.getDetails(); //Calling to get the details
"John is 24 years old." //Output
Explanation of above example:
In the above example, we have defined a class details in which we have declared private variables as name and age. We have also defined inner functions or closures and declared them public using this keyword. Practically in encapsulation we encapsulate certain properties of the class (name and age in this case) so that it cannot be accessed directly, to access these properties we create certain functions known as setter-getter. Here these functions are inner functions or closures(setDetails & getDetails) which are declared as public using this keyword.
setDetails is the function which sets the values of the private properties and can be used anywhere within the application.
getDetails is the function to get the values of private properties of the class. We cannot access private properties or private variables (name and age) directly, lets consider if we write a code like,
var mydetails = new details();
mydetails.name;
It will give undefined as name is a private variable and cannot be accessed directly.
In this way, we can encapsulate certain properties of the class and make it accessible using inner functions or closures which are declared as public using this keyword.
Concept of this keyword in javascript
this refers to the current context. Context is based on namespace, for instance, if the namespace is object or constructor function then this will refer to context of that particular object or constructor function. If there is no namespace explicitly defined then this will refer to the global namespace, i.e. window object.
Behaviour of this when object as namespace:
var obj = {
myfunc: function() {
console.log(this);
}
}
myfunc: function() {
console.log(this);
}
}
obj.myfunc(); // prints the obj in the console as obj {myfunc : f }
Behaviour of this when constructor function as namespace:
var obj = function() {
this.myfunc = function() {
console.log(this);
}
console.log(this);
}
}
var myobj = new obj(); //creating an object of obj
myobj.myfunc(); //prints the obj in the console as obj {myfunc : f}
myobj.myfunc(); //prints the obj in the console as obj {myfunc : f}
Behaviour of this when there is global namespace:
function myfunc() {
console.log(this);
}
myfunc(); // prints the window object as window{postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
console.log(this);
}
myfunc(); // prints the window object as window{postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}


Comments
Post a Comment