JavaScript : Closure Program

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();

function myFunction(){
document.getElementById(“demo”).innerHTML = add();
}

Example Explained

The variable add is assigned the return value of a self-invoking function.

The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

This way add becomes a function. The “wonderful” part is that it can access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have “private” variables.

The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

A closure is a function having access to the parent scope, even after the parent function has closed.

GoLang : Closure program

Hi Friends,

Here is a sample closure program. A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

package main

import "fmt"

func closureFunc() func() int {
       fmt.Println("init the x ")
       x := 1
       return func() int {
              x++
              return x
       }
}

func normalFunc() int {
       x := 100
       x++
       return x
}

func main() {
       increment := closureFunc()
       fmt.Println(increment())
       fmt.Println(increment())
       num := normalFunc()
       fmt.Println(num)
       increment1 := closureFunc()
       fmt.Println(increment1())
       fmt.Println(increment1())
       fmt.Println(increment())
}

/*
closure helps us limit the scope of variables used by multiple functions
without closure, for two or more funcs to have access to the same variable,
that variable would need to be package scope
*/

 

 

MongoDB : Exporting JSON with mongoexport

This will export a JSON representation of the database. Note that as a rule – particularly for backing up or moving data – MongoDB recommends the “dump and restore” approach as BSON can contain more rich data than JSON. Nevertheless, mongoexport still has its uses, sometimes a JSON representation of the data is very useful – it’s what we’ve been using so far in the application development.

Basic output to console

Need to specify the name of the database –db and the collection –collection to export. Restoring dumped data with MongoRestore Inserts only, no updates Exporting JSON with mongoexport

Basic output to console

> mongoexport –db meantest –collection tech

Send to a file

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json

Create as array

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json –jsonArray

Make output pretty

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json –jsonArray –pretty

 

MongoDB : How to take export a database using mongo dump

We need to take database backup or have to export specific database in  mongo

This command will export specific databases in mongo and export to home folder /dump

> mongodump –db testDatabase

# to compress in zip file and folder

> mongodump –db testDatabase   –gzip

> cd ~/dump

This command will restore or import specific db

>mongorestore –db testDatabase   –gzip  ~/dump/testDatabase

Note :

There command should be run from command prompt / shell and not from mongo sheel.

Mongo restroe does not update existing collections

Javascript : Non blocking / Async example

/**
 * Created by Aseem on 12/7/16.
 */

console.log("1: Start app")

var slowProcess = setTimeout(function(){
    console.log("2: app processing async - non blocking ");
},1000);

console.log("3: Exit app")

 

The out of this is non blocking, which mean the flow will not wait  or get blocked for slowProcess

Sample console output

➜ async git:(master) ✗ node nonBlocking.js
1: Start app
3: Exit app
2 : app processing async – non blocking

 

Motivating story – Honesty Pays

At the point of death a man, Tom Smith, called his children and after praying for them, he advised them to follow his footsteps so that they can have peace of mind in all that they do.

The youngest child, Immaculate, a female, looked at others and yeled, “Daddy, its unfortunate you are dying without a penny in your bank account, personally, I can’t emulate you. Other father’s that you tag as being corrupt, thieves of public funds left houses and properties for their children; even this house we live in is a rented apartment, sorry, i can’t emulate you, just go, let’s chart our own course, let’s paddle our own canoe.”

Few moments later, their father gave up the spirit.

Three years later, Immaculate went for an interview in a multinational company. The interview panel had already penciled down a candidate for the highly coveted post but wanted to complete the formality of interviewing all applicants on the list.

As soon as Immaculate sat before the interview panel, the Chairman of the committee asked, “Which Smith is yours” and
Immaculate replied, “I am Immaculate Smith. My Dad Tom Smith is now late he died a poor man…”

But the Chairman cuts in, “O my God, you are Tom Smith’s daughter? ”

He turned to other members and said “This Smith man was the one that signed my membership form into the Institute of Chartered Administrators and his recommendation earned me where I am today.

He did all these free. I didn’t even know his address, he never knew me from Adam. He just did it for me.”

He turned to Immaculate, I have no question for you, consider yourself as having gotten this job, resume tomorrow, your letter will be waiting for you.

Immaculate Smith became the Corporate Affairs Manager of the
company with two cars, one official and one for private use, attached to the office, with a duplex and two drivers and a salary of £100,000 per month excluding allowances and other costs when she travelled outside England.

After two years of working in the company, the Group Managing Director of the company came from America to announce his intention to resign and needed a replacement. A personality with high integrity was sought after, again the company’s Consultant nominated Immaculate Smith.

In an interview, she was asked the secret of her success and the sudden sky rocketing profile and in tears, she replied, my Daddy paved these ways for me. It was after he died that I knew that he was financially poor but stinkingly rich in integrity, discipline and honesty.

She was asked again, why she is weeping since she is no longer
a kid as to miss her dad still after a long time.

She replied, “At the point of death, I insulted my dad for being an honest man of integrity. I hope he will forgive me in his grave now.

I didn’t work for all these, he did it for me to just walk in.

So finally she was asked,” Will you follow your father’s foot steps as he requested?

And her simple answer was, “l now adore the man, I have a big picture of him in my living room and at the entrance of my house. He deserves whatever I have after God.

Are you like Tom Smith?
It pays to build a name, the reward doesn’t come quickly but it will come however long it may take and it lasts longer.

Integrity, discipline, self control and fear of God makes man wealthy, not the fat bank account.

Leave a good heritage for your children.

Are you building a good name for your children not a fat bank account?

As an agent of CHANGE, please share this true life story with your loved ones. God bless us all.

GIT : Generate git Ignore file using online tool -> gitignore.io

Hi Friends,

When we create project using IDE like eclipse, web storm, intellij, a lot of additional files shows up other then required code base. Best practice is to add “.gitignore” file, mention the pattern of (non required) files and commit it. That way git will ignore those file and will not track any changes for those file.

To generate the pattern, you can take help of below online tool, this will give you .gitignore file which can be added and used.

https://www.gitignore.io