Search This Blog

Monday, October 8, 2018

Javascript : Array - map ,reduce,filter


Map, Reduce and Filter are Array methods each one will iterate over an array
and perform a transformation or computation.They are all 'higher order'
functions because they take user-defined functions as parameters.


Map:
The map() method is used for creating a new array from an existing one by
applying a callback function to each one of the elements of the first array.

Detailed Syntax for map function in javascript is

array.map(callback(currentValue, index, array), thisArg)

or

array.map((currentValue, index, array)={
//operate on input & return
}, thisArg)

Here's what each part of the syntax represents:

array: The array on which the map() method is called.

callback: A function that will be called once for each element in the
array.It can take up to three arguments:

currentValue: The current element being processed in the array.

index (optional): The index of the current element being processed.

array (optional): The array map() was called upon.

thisArg (optional): An optional parameter that defines the value to be
used as this inside the callback function.

Code:
const person = {
firstName: "John",
lastName: "Doe",
fullName() {
return this.firstName + " " + this.lastName;
},
};

const people = [
{ firstName: "Alice", lastName: "Smith" },
{ firstName: "Bob", lastName: "Johnson" },
];

const fullNames = people.map(function (item) {
return (
this.fullName() + " works with " + item.firstName + " "
+ item.lastName
);
}, person); // Here, 'person' is passed as the 'thisArg'

console.log(fullNames);
Output:
[
'John Doe works with Alice Smith',
'John Doe works with Bob Johnson'
]
Explanation:
Here person is passed as the 'thisArgs',so when this.fullName() is called
it do all calculation based on person object.

In common uses of map() the 'thisArgs' is rarely passed also index,array
argument are also rare.

Below are common use cases on map().

First Creating Function and then passing it to map() function as callback:
Code:
var arr=[16,25,36,49,64]

function sqrRoot(item){
return Math.sqrt(item)
}

var result = arr.map(sqrRoot)
console.log(result)

Output:
[ 4, 5, 6, 7, 8 ]

Passing callback function to map() function without creating it seperately:
Code:
var arr = [16, 25, 36, 49, 64];

var result = arr.map(function sqrRoot(item) {
return Math.sqrt(item);
});

console.log(result);
Output:
[ 4, 5, 6, 7, 8 ]

Passing a ananomous function as callback to map() function:
Code:
var arr = [16, 25, 36, 49, 64];

var result = arr.map(function(item) {
return Math.sqrt(item);
});

console.log(result);
Output:
[ 4, 5, 6, 7, 8 ]

Passing a lambda function as callback to map() function
Code:
var arr = [16, 25, 36, 49, 64];
var result = arr.map((item) => Math.sqrt(item));

console.log(result);
Output:
[ 4, 5, 6, 7, 8 ]

same lambda function can be written with a block of code enclosed in
curly braces, and return statement.

Code:
var arr = [16, 25, 36, 49, 64];
var result = arr.map((item) => {
return Math.sqrt(item)
});
console.log(result);
Output:
[ 4, 5, 6, 7, 8 ]


Note:
The result of map() is always a new array, not an object.
To transform an array into an object, you would typically
use other methods like reduce()

Reduce:
The reduce() method reduces an array of values down to just one value.
To get the output value, it runs a reducer function on each element of
the array.

Here's the syntax for the reduce() method:

array.reduce(callback(accumulator, currentValue, index, array), initialValue)

or

array.reduce((accumulator, currentValue, index, array)=.{
//do some acttion & return
}, initialValue)

Here's what each part of the syntax represents:
array: The array on which the reduce() method is called.

callback: A function that will be called once for each element in the
array,taking up to four arguments:

accumulator: The accumulator accumulates the callback's return values.
It is the accumulated value previously returned in the last invocation
of the callback,or initialValue if provided.

currentValue: The current element being processed in the array.

index (optional): The index of the current element being processed.

array (optional): The array reduce() was called upon.

initialValue (optional): A value to use as the initial value of the
accumulator. If not provided, the first element in the array will be
used as the initial accumulator value and skipped as the currentValue.

Below is an example of reduce() function.

Code:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 10);
console.log(sum);

Output:
25

Explanation:
Here accumulator has initial value of 10,in each interation
currentvalue is getting added to accumulator value.

Here are some variants of same code
Variant 1:
Code:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
accumulator = accumulator + currentValue;
return accumulator
}, 10);
console.log(sum);
Output:
25

Variant2:
Code:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator = accumulator + currentValue;
}, 10);
console.log(sum);
Output:
25
reduce() can be used to transform an array of strings into a single object
that shows how many times each string appears in the array.

Code:
let pets = ["dog", "chicken", "cat", "dog", "chicken", "chicken", "rabbit"];

let petCount = pets.reduce((accumulator, currentValue) => {
if (accumulator[currentValue] == undefined) {
accumulator[currentValue] = 1;
} else {
accumulator[currentValue] = accumulator[currentValue] + 1;
}
return accumulator
}, {});

console.log(petCount);
Output:
{ dog: 2, chicken: 3, cat: 1, rabbit: 1 }

Here is another example of reduce

Code:
let pets = [
["dog", "med"],
["chicken", "feathury"],
["cat", "bil"],
["dog", "bob"],
["chicken", "minny"],
["chicken", "shelly"],
["rabbit", "binny"],
];

let petCount = pets.reduce((accumulator, currentValue) => {
var elem = {"type":currentValue[0],"name":currentValue[1]}
accumulator.push(elem)
return accumulator;
}, []);

console.log(petCount);

Output:
[
{ type: 'dog', name: 'med' },
{ type: 'chicken', name: 'feathury' },
{ type: 'cat', name: 'bil' },
{ type: 'dog', name: 'bob' },
{ type: 'chicken', name: 'minny' },
{ type: 'chicken', name: 'shelly' },
{ type: 'rabbit', name: 'binny' }
]

You can use the reduce() method in JavaScript to convert an array into an
object by accumulating key-value pairs from the array elements.

Here's an example of how to do that:
Code:
const array = [
{ key: 'name', value: 'John' },
{ key: 'age', value: 30 },
{ key: 'city', value: 'New York' }
];

const obj = array.reduce((acc, item) => {
acc[item.key] = item.value;
return acc;
}, {});

console.log(obj);

Output:
{ name: 'John', age: 30, city: 'New York' }

Filter:
The filter() method takes each element in an array and it applies
a conditional statement against it. If this conditional returns
true, the element gets pushed to the output array. If the
condition returns false, the element does not get pushed to
the output array.

Syntax of filter method:

array.filter(callback(element, index, array), thisArg)
or
array.filter((element, index, array)=>{
//do something with input & return
}, thisArg)

Here's what each part of the syntax represents:

array: The array on which the filter() method is called.
callback: A function that will be called once for each
element in the array, taking up to three arguments:
element: The current element being processed in the array.

index (optional): The index of the current element being processed.

array (optional): The array filter() was called upon.

thisArg (optional): An optional parameter that defines the value to
be used as this inside the callback function.

Example of filter with thisArg:
Code:
const numbers = [1, 2, 3, 4, 5];
const thresholdFilter = numbers.filter(function(element) {
return element > this.threshold;
}, { threshold: 3 });
console.log(thresholdFilter); // Output: [4, 5]
Output:
[4,5]
Explanation:
Here thisArg is { threshold: 3 }.we can get value from thisArg in callback
function inside this.If callback function is not normal function but arrow
function them we will not get anything in this hence it is undefined.

Doing same code using lambda function:
Code:
const numbers = [1, 2, 3, 4, 5];
// Create an object with the threshold property
const context = { threshold: 3 };
const thresholdFilter = numbers.filter((element) => {
return element > context.threshold;
});

console.log(thresholdFilter); // Output: [4, 5]
Output:
[4,5]

Explanation:
Here we are not passing thisArg instead we are using a context object
defined in outer scope
Common example of reduce:
Code:
const numbers = [1, 2, 3, 4, 5];
var even = numbers.filter((m) => {
return m % 2 == 0;
});
console.log(even);
Output:
[2,4]

Explanation:
numbers array get filtered we get even as for any number(m), m%2==0
only when it is even.

Saturday, October 6, 2018

REST Based CRUD API for Postgres & Express.js

Lets first create table in database required in article.


create table course(id varchar(50),name varchar(500),primary key(id))

insert into course values(1,'C'),(2,'CPP'),(3,'C#'),(4,'python'),(5,'Ruby')



now create PgUtil.js


const pgp = require('pg-promise')(/* initialization options */);


const cn = {

host: 'localhost', // server name or IP address;

port: 5432,

database: 'sangram',

user: 'xdba',

password: 'sangram'

};

const db = pgp(cn); // database instance;



var PgUtil = {

executeQuery: async function (sqlQuery, callback) {

var result = await db.any(sqlQuery)

console.log(result);

callback(null,result)

},


executeNonQuery: async function (sqlQuery, callback) {

var result = await db.none(sqlQuery)

console.log(result);

callback(null,result)

}

}


module.exports = PgUtil




Inside routes add course.js

var express = require('express');

var router = express.Router();

var PgUtil = require('../PgUtil');




/*getbyid */

router.get('/:id?', function (req, res, next) {

var queryString = ''

if (req.params.id) {

queryString = "select * from course where id= '" + req.params.id + "'"

} else {

queryString = "select * from course "

}

console.log(queryString);

PgUtil.executeQuery(queryString, function (err, data) {

if (err) {

res.json(err);

} else {

res.json(data)

}

})



});


/*update*/

router.put('/:id', function (req, res, next) {

console.log(req.body);

var queryString = "update course set name='" + req.body.Name + "' where id= '" + req.params.id + "'"

PgUtil.executeNonQuery(queryString, function (err, data) {

if (err) {

res.json(err);

} else {

res.json({

"message": "row updated successfully"

})

}

})



});


//insert

router.post('/', function (req, res, next) {

var queryString = "insert into course(id,name) values('" + req.body.Id + "','" + req.body.Name + "')"

console.log(queryString);


PgUtil.executeNonQuery(queryString, function (err, data) {

if (err) {

res.json(err);

} else {

res.json({

"message": "row inserted successfully"

})

}

})

});


/*delete */

router.delete('/:id', function (req, res, next) {

var queryString = "delete from course where id= '" + req.params.id + "'"

console.log(queryString);

PgUtil.executeNonQuery(queryString, function (err, data) {

if (err) {

res.json(err);

} else {

res.json({

"message": "row deleted successfully"

})

}

})

});


module.exports = router;




Now we are done ,run "npm start"


On Postman


1) GET : http://localhost:3000/course

will list all course

2) GET :http://localhost:3000/course/1

will list course with id 1

3) POST:http://localhost:3000/Course

Header:Content-Type:application/json

Body:

{

"Id":"7",

"Name":"Java"

}

will add new course

4)PUT:http://localhost:3000/Course/4

Header:Content-Type:application/json

Body:

{

"Name":"Java"

}

will update course with id 4 its name to java from old value


5) Delete: http://localhost:3000/Course/5

will delete course record with id as 5


Code of this article can be viewed at https://github.com/gitsangramdesai/express-pg-rest

REST Based CRUD API for Mysql & Express.js

First we will create a table in mysql for purpose of mysql crud demonstration.

CREATE TABLE IF NOT EXISTS `course` (  `Id` varchar(50) NOT NULL,  `Name` varchar(500) DEFAULT NULL,  PRIMARY KEY (`Id`)  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Add Some Entries into course table

    insert into course values(1,'C');
    insert into course values(2,'CPP');
    insert into course values(3,'C#');
    insert into course values(4,'Python');
    insert into course values(5,'Ruby');
    insert into course values(6,'Java');


create express project by  running
     express --view=ejs mysqlcrud

install packages with
    npm install

Now
      dbconnection.js as follows

    var mysql = require('mysql');
    var connection = mysql.createPool({
        host: 'localhost',
        user: 'xdba',
        password: 'Sangram@123',
        database: 'play'
    });
    module.exports = connection;

Create a folder called models and add file "Course.js" with following content

var db = require('../dbconnection'); //reference of dbconnection.js

    var Course = {
        getAllCourses: function (callback) {
        return db.query("Select * from course", callback);
        },
        getCourseById: function (id, callback) {
        return db.query("select * from course where Id=?", [id], callback);
        },
        addCourse: function (Course, callback) {
        return db.query("Insert into course values(?,?)", [Course.Id, Course.Name], callback);
        },
        deleteCourse: function (id, callback) {
        return db.query("delete from course where Id=?", [id], callback);
        },
        updateCourse: function (id, Course, callback) {
        return db.query("update course set Name=? where Id=?", [Course.Name, id], callback);
        }
    };
    module.exports = Course;


add file course.js in route folder as
    var express = require('express');
    var router = express.Router();
    var Course = require('../models/Course');


    /*getbyid */
    router.get('/:id?', function (req, res, next) {
      if (req.params.id) {
        Course.getCourseById(req.params.id, function (err, rows) {
          if (err) {
        res.json(err);
          } else {
        res.json(rows);
          }
        });
      }else {
        Course.getAllCourses(function (err, rows) {
          if (err) {
        console.log("error");
        res.json(err);
          } else {
        res.json(rows);
          }
        });
      }
    });

    /*save new */
    router.post('/', function (req, res, next) {
      console.log(req.body);
      Course.addCourse(req.body, function (err, count) {
        if (err) {
          res.json(err);
        } else {
          res.json(req.body);//or return count for 1 & 0
        }
      });
    });

    /*delete */
    router.delete('/:id', function (req, res, next) {
      Course.deleteCourse(req.params.id, function (err, count) {
        if (err) {
          res.json(err);
        } else {
          res.json(count);
        }
      });
    });

    /*update*/
    router.put('/:id', function (req, res, next) {
      Course.updateCourse(req.params.id, req.body, function (err, rows) {
        if (err) {
          res.json(err);
        } else {
          res.json(rows);
        }
      });
    });

    module.exports = router;

in app.js below "var users = require('./routes/users');" add

    var course = require('./routes/course');
and in app.js below "app.use('/users', users);" add
    app.use('/course', course);

Now we are done ,run "npm start"


On Postman

1) GET : http://localhost:3000/course
    will list all course
2) GET :http://localhost:3000/course/1
    will list course with id 1
3) POST:http://localhost:3000/Course
   Header:Content-Type:application/json
   Body:
    {
    "Id":"7",
    "Name":"Java"
    }
   will add new course
4)PUT:http://localhost:3000/Course/4
   Header:Content-Type:application/json
   Body:
    {
    "Name":"Java"
    }
   will update course with id 4 its name to java from old value

5) Delete: http://localhost:3000/Course/5
    will delete course record with id as 5

code sample can be viewed at  https://github.com/gitsangramdesai/mysql-crud-express