longest word in the sentence

find longest word in the sentence

Find the longest word in the sentence

I am using javascript for this question.

It can be done in a lot of ways. The straight forward way could be the fastest probably. You will loop over the array of the words – you can split it with space – ” “.

Then just compare the value of the word length with maximum value and overwrite when it is higher – you know what I mean..

I will show the single liner for this though


var longestWord = "Guess what the longest word in the dictionary is".split(" ").sort(function(a, b){
    return b.length - a.length;
})[0];

Let’s go through what is going on..

The first part "Guess what the longest word in the dictionary is" is the given example sentence we are trying to find the longest word for.

Then we split the string into array of words using the split(" ") function. Now we have array to work with.

Then we sorted the array with sorter function passed to it. Sorter function in this one is anonymous function that we pass to it.

Finally we just took the first element of the sorted array which is sorted by the length of the word.

Also with the same concept, we have have it using reduce function;

"I still am having the wonderfulness of this thing ".split(" ").reduce((word1, word2) => word2.length > word1.length ? word2 : word1 );

That is it!

Max string character counting

Get maximum occurring character

Find maximum occurring character from the given string

Max occurring character is the most frequent interview whiteboard question. Ok, there are so many of ways to handle this question and this is just one of them.

I have showed it with 6 characters as starting point and use those as reference. But you can extend that given object to hold as many characters as you want.
Continue reading Get maximum occurring character

Flatten nested javascript array

How do you flatten array in javascript

If you are given an array that contains literals, arrays and objects and you want to get all the values to one array.

Here is the snippet using recursive function to attain that.


function implode(arr) {
	var res = [];
	for (var i =0; i < arr.length ; i++) {
    	if (Array.isArray(arr[i])) {
        	res = res.concat(implode(arr[i]));
		} else if(typeof arr[i] == 'object' ) {
			var values = Object.values(arr[i]);
        	for (var j = 0 ; j < values.length ; j++) {
            	if (!Array.isArray(values[j]) && typeof values[i] != 'object') {
					res.push(values[j]);
                }else{
                	res = res.concat(implode(values[j]));
				}
			}
		} else {
			res.push(arr[i]);
        }
	}
	return res;
} 

javascript queue and stack implementation

Implement Queue Using two Stacks – JavaScript algorithm

Using stack data structure to implement queue in javascript

This is one way of implementing of the stack to be reused as queue using two stacks.

You may complain you are abusing the memory. But we are not copying the data on both stacks we are using the stacks for switching values only


            class Queue {
                constructor() {
                    this.inputStack = [];
                    this.outputStack = [];
                }

                enqueue(item) {
                    this.inputStack.push(item);
                }

                dequeue(item) {
                    this.outputStack = [];
                    if (this.inputStack.length > 0) {
                        while (this.inputStack.length > 0) {
                            this.outputStack.push(this.inputStack.pop());
                        }
                    }
                    if (this.outputStack.length > 0) {
                        console.log(this.outputStack.pop());
                        this.inputStack = [];
                        while (this.outputStack.length > 0) {
                            this.inputStack.push(this.outputStack.pop());
                        }
                    }
                }

                listIn() {
                    let i=0;
                    while(i < this.inputStack.length) {
                        console.log(this.inputStack[i]);
                        i++;
                    }
                }
                listOut() {
                    let i=0;
                    while(i < this.outputStack.length) {
                        console.log(this.outputStack[i]);
                        i++;
                    }
                }
            }

*There is part left out for improvement and refactoring. But, can you see a way to use only one while rather than two whiles and make it a bit efficient?

Check if Function Exists in Javascript

How to check if function exists in javascript

Javascript might not be happy if you call function before it is being created. This can happen in a couple of cases.

You might be wondering how to check if function exists in javascript before calling it.

Lets say you have a onLoad logic, and there could be function definition below it. In that case, if you try to call the function from the onLoad, it might complain as

Uncaught referenceError: functionName is not defined 

This happens only because the browser will be creating the function later and there is no precedence on this.

How to fix Uncaught referenceError: is not defined javascript error

In this case you can check if the function exists first and call it afterwards:


if (typeof functionName == 'function') {
    functionName();
}

This will solve the problem. But there is a catch, you need to recall it again you make sure it is loaded.

Let me know if this solves your problem or not. I can add more based on your questions or suggestions.

jQuery Select Option from Json

jQuery select option population using json as data source

jQuery select option tutorial will show how you can glue together the following terms together

  • select box
  • JSON
  • jQuery
  • *Javascript

* You might ask isn’t jQuery javascript? Yes indeed you are right, but jQuery is a framework making javascript programming a lot easier.

When I say plain javascript, or as some are calling it old school javascript, I meant to use the same task without using jQuery.

What select box is and types of select box options

Select box is one of the most used HTML element along with text input, radio option and the like.

Select box will allow you to provide dropdown options where you can select one or more items from it. You can make the select box to allow multiple selection using multiple attribute


Continue reading jQuery Select Option from Json

using mongodb with nodejs and angular js

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

This is a final part of the node angular and mongodb tutorial.

So far each part of the whole process has been shown by far. This is a part showing how the data would be pulled and shown to the angular based page.

Mind you, in this tutorial, the page was getting the list from the hard coded array and that is simply changed to the array that is read from mongodb. That part can be hooked to other datasources like MsSQL server or MySQL or anything.

Using MongoDB in Node JS

1. Create a folder named node-mongo

2. install mongodb and express packages there

sudo npm install express
sudo npm install mongodb

*I will have another tutorial showing how to use the package manager using package.json. But for now just install the packages like the one I showed above.

3. create server.js in node-mongo folder and add the following content in it


var express = require('express');
var app = express();

//connection string for mongo
var mongoPath = "mongodb://localhost:27017/nodemongo";
//require mongo and get the client.
var mongoClient = require('mongodb').MongoClient;

//a router for the home page. "/" being the home page
app.get("/", function(request, response){
    response.sendFile(__dirname + "/views/home.html");
});

//a router for listening to /listcountries 
app.get("/listcountries", function(request, response){

    // mongo connection comes from here
    mongoClient.connect(mongoPath, function(error, database){
        var result = {};
        
        //once connected, then get the row from mongo database. find() would list all
        if (error) {
            result.message = "Connection error";
            response.send(result);
        } else {
            var collection = database.collection("countries");
            collection.find().toArray((err, listOfCountries)=>{
                response.send({"list":listOfCountries});
            });
        }
    });    
});

app.listen(8080);
console.log("serving web on port 8080");

By now, most of the usages on this file would be easy to understand if you have followed the previous tutorials.

How to install mongo in the computer and how to add some collections to it and the like is beyond the scope of this tutorial and I assume you have already installed mongo on your system and have created a database and collection with it.

In the example above, I have used mongo database named nodemongo and collection countries

4. create a folder views in node-mongo

5. create a file home.html and add the following code in in it


<html>
<head><title>Countries</title></head>
<body ng-app="NodeMongoApp">
<h2>here you would unleash the science of listing countries</h2>
<div ng-controller="MongoController">
    <a href="#" ng-click="listCountries()">list countries</a>

    <ul ng-repeat="country in countries">
        {{country.name}}
    </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
    var app = angular.module("NodeMongoApp", []);
    app.controller("MongoController", function($scope, $http){
        
        $scope.listCountries = function() {
            $http.get("/listcountries").success(function(countries){
                $scope.countries = countries.list;    
            });
        };
    });
</script>
</body>
</html>

That is it.

Now you will want to be in the node-mongo folder and issue

node server.js

and from your browser, go to http://localhost:8080

You can download the whole project here

using angular js with node js application example

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Take a look on this tutorial and I will use the same setup with it

Follow until step 5 from the above example.

If you see the server.js, it will populate the hardcoded countries the template file countries.ejs file.

But this time, we dont need the ejs file at all, rather all what is needed from the node js server is to provide the json formatted response of the countries.

In the server.js file, add the following code


var express = require("express");
var app = express();

app.set("views", __dirname + '/views');

app.get("/", function(request, response){
   response.sendFile(__dirname + '/views/index.html'); 
});

app.get("/listcountries", function(request, response){
    var title = "List of Countries";
    var hardCodedCountries = [{"name":"America","population":300}, {"name":"Britain","population":53},{"name":"Canada","population":35},{"name": "Democratic Congo","population":67},{"name": "Ethiopia","population":90}, {"name":"Finland", "population":5}, {"name":"Gabon", "population": 2}];
    response.send(hardCodedCountries);
});

app.listen(8080);
console.log("Hit http://localhost:8080");

On this one, the view engine is removed and also the response.render is replaced by response.send

In short, the node has created an endpoint named /listcountries that would list countries and send that to the requester.

6. Now, the next task would be to update the page that would list the countries using angular

update the index.html file in views folder as follows


<html>
<head><title>Node with template</title></head>
<body ng-app="AngularNodeApp">
<div ng-controller="CountryController">
	<h2>Listing countries has never been easy</h2>
	<a href="#" ng-click="listCountries()">List Countries</a>

	<div>
	<ul ng-repeat="country in countries">
		<li>{{country.name}} | {{country.population}}</li>
	</ul>
	</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var app = angular.module("AngularNodeApp", []);
app.controller("CountryController", function($scope, $http){
	//get the list of countries
	$scope.listCountries = function() {
                //call the API to listcountries and get the list of countries as json response
		$http.get("/listcountries").success(function(countries_from_node){
                //assign countries variable that is accessed through $scope
		$scope.countries = countries_from_node;
		});
	};
});
</script>
</body>
</html>

Here it is clear that, the front and backend are separated in that the front end would act in its own by requesting what it needs from the backend only. As long as the node js is responding the list through its listcountries

Next: Using mongo db in the angular node js application

introduction to Angular js for usage of node js

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

I might not go over the basics of angular js here except what is needed for the tutorial.

The main idea in using Angular js would be to make sure the front end and back end are completely separated and they would be talking each other through end points that are designated through node js.

Angular basics

Angular is an MVC architecture oriented javascript framework. I will have some example that would illustrate that as a basic introduction.


<html>
	<head><title>Testing angular</title></head>
	<body ng-app="HelloTest">
        
		<div ng-controller="HelloController">
			<p>{{concat}}</p>
		
            <div> <input type="text" ng-model="color" ng-keyup="updateColor()" name="color" /></div>
            <div> The selected color is {{current_color}} </div>
        </div>

	    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>  
        <script>
		    angular.module("HelloTest", []).controller("HelloController", function($scope){
                $scope.concat = "Whatever goes here";    
                $scope.updateColor = function () {
                    $scope.current_color = $scope.color;
                };
            });
	    </script>
    </body>
</html>

Save the above code in a file angular.html and just double click on it to see it running.

The above simple example shows a basic usage of events in Angular js. All it does is printing whatever you put in the text box as color.

Basic points in the Angular application

ng-app="HelloApp" : this would be assigned usually on the root of the html dom. It tells that pages is under the given ng-app. See how that name aligns with the name angular.module("HelloApp")

ng-controller The app can contain a number of controllers under it. A controller is the one that sits between the view and logic that would fill up the view. in this example, the ng-controller="HelloController" will be used for the directive it has been defined. In this example for the whole element of the div it has been declared for.

You can have as many controller as you want in the given app


//create the application here
var app = angular.module("HelloTest", []);

//create the controller.
app.controller("HelloController", function($scope){
                $scope.concat = "Whatever goes here";    
                $scope.updateColor = function () {
                    $scope.current_color = $scope.color;
                };
            });

//create another controller.
app.controller("AnotherController", function($scope){
                $scope.concat = "In another controller";    
            });

The above shows how you can have more than one controller in the app.

$scope is the special variable passed around that would give the whole scope that the controller has authority of.

the {{ }} is the place holder that would be assigned the value from the controller. In the example above, concat and current_color are the ones to be assigned from the controller and get their values being assigned where ever they are.

Angular has lots and lots of directives for the condition, loop and the like

Next: get the list of countries from node and showing them using Angular example

Using template engine in node js to render response values example

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

In this tutorial, the user input was accepted and processed, but the result was not sent to another html page that contains the result.

In real world application that is common task, say if you have a page listing the name of countries by reading them from data source, the returned page should populate the list of countries with probably other information which is well formatted with css and even some javascripts.

For this, the node has provided the templating engine.

What the template engine does is, it will put some placeholders for the variables that are sent from the server, process them and will finally output html file.

There are many template engines out there for node, I have used ejs since it is easy to use and has similarity with HTML and javascript.

Using template engine in node js to render html pages

1. create a directory node-template

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. install ejs template engine

sudo npm install ejs

5. create server.js in node-template folder and add the following code in it


var express = require("express");
var app = express();

app.set("view engine", "ejs");
app.set("views", __dirname + '/views');

//router for the home page
app.get("/", function(request, response){
   //this doesn't need anything to be rendered so it is provided simple html file
   response.sendFile(__dirname + '/views/index.html'); 
});

//router for listcountries path
app.get("/listcountries", function(request, response){
    var title = "List of Countries";
    //instantiate the list of countries from hard coded array
    var hardCodedCountries = [{"name":"America","population":300}, {"name":"Britain","population":53},{"name":"Canada","population":35},{"name": "Democratic Congo","population":67},{"name": "Ethiopia","population":90}, {"name":"Finland", "population":5}, {"name":"Gabon", "population": 2}];
    response.render("countries", {'countries': hardCodedCountries, 'title': title});
});

app.listen(8080);
console.log("Hit http://localhost:8080");

From the above code, the part

app.set("view engine", "ejs");
app.set("views", __dirname + '/views');

Tells the node what template engine we are using and where the template pages are supposed to be residing. The __dirname is the current directory of the running script

Another point is, you see response.render that is where the ejs would be useful. It would take the countries list and iterate through them to display. The hardCodedCountries and title are computed values that are passed to the template file.

Further ejs syntax and usage can be seen here

6. Create file countries.ejs and add the following code in it.


<html>
<head><title>With template engine</title></head>
<body>
<h2><%= title %></h2>
<table>
<% for(var i=0; i<countries.length; i++) {%>
   <tr><td><%= countries[i].name %> </td>
        <td><%= countries[i].population %> million </td></tr>
   <% } %>
</table>
</body>
</html>

7. Then being in the node-template folder, run

node server.js

This would require, as you can see it, having the pages tightly coupled with the logic and that is not good.

What is needed for this then is, a separate front end from the nodejs

Next: Quick introduction to Angular js