Map vs Reduce vs Filter in JavaScript

So these methods are part of the “functional” aspect of JavaScript. JavaScript is a strange language in a good way. Before we get into this, know that all these methods above try to replace the “for” loop, or any other type of loop you can think of.

Some of you might be saying, “I like my loops thank you very much, it is in every language out there !”. And yes that is very true, however these make writing a whole loop for something trivial a thing of the past. So lets get on with it, its not as hard as you probably things it is.

All these methods only working on arrays. And they never modify the array you apply them to. They just return a new array.

MAP

As in Mapping “X” to “Y”, or transforming X into Y. In the case of JavaScript you are making a map of your values. You basically just give it a function (could be anonymous) and it applies it to each array element, and forms a new array.

// Array you wanna do the operation on
const peopleArray = [ {Name: "Tim", BankBalance: 10},
{Name: "Leo", BankBalance: 20},
{Name: "Sam", BankBalance: 30} ];
// calling the Map function and having it return its value into
// reformattedArray. Where "obj" represents each object in the
// peopleArray
let reformattedArray = peopleArray.map((obj) =>{
let newObj = {};
newObj.Name = "Mr." + obj.Name;
newObj.BankBalance = obj.BankBalance * 1000;
return newObj;
});
console.log(reformattedArray);
// "reformattedArray" is now: [ { Name: 'Mr.Tim', BankBalance: 10000 },
// { Name: 'Mr.Leo', BankBalance: 20000 },
// { Name: 'Mr.Sam', BankBalance: 30000 } ]
// you can also get another parameter that is passed in. Known as the index
// of the object in the old array (peopleArray in this case)
reformattedArray = peopleArray.map((obj, index) =>{
let newObj = {};
newObj.MyIndex = index;
newObj.Name = "Mr." + obj.Name;
newObj.BankBalance = obj.BankBalance * 1000;
return newObj;
});
console.log(reformattedArray);
// "reformattedArray" is now:[ { MyIndex: 0, Name: 'Mr.Tim', BankBalance: 10000 },
// { MyIndex: 1, Name: 'Mr.Leo', BankBalance: 20000 },
// { MyIndex: 2, Name: 'Mr.Sam', BankBalance: 30000 } ]

view raw
MapsInJS.js
hosted with ❤ by GitHub

REDUCE

As in reducing something to its essence, or compressing something down. In the case of JavaScript you are taking all your values in an array, and compressing them into something useful.

// Here we have a list of all the transactions made by Mike
const transActionsForMike = [ {Name: "Bike", Cost: 5000},
{Name: "Apple Music", Cost: 20},
{Name: "Cook Book", Cost: 30},
{Name: "Azure Hosting", Cost: 60},
{Name: "Phone Bill", Cost: 70}];
// And we try to figure out how much Mike Spent
// "reduce" takes in three main arguments, the Accumulator (acc), the
// currentValue (curr) in the form of an anonymous function. And a inital
// value for the accumulator (in our example its 0). The accumulator acts
// like a bucket that you keep adding things to. Or keep modifying every
// interaction of the reduce function.
// Here we are taking each object in the "transActionsForMike" variable. Then
// we are accessing the cost property of each object, then continuously adding it to
// the accumulator.
// then at the very end we are returning the accumulator that gets dumped into the
// MikesSpending variable.
let MikesSpending = transActionsForMike.reduce((acc, curr) =>{
return acc + curr.Cost;
}, 0);
console.log(MikesSpending) // MikesSpending is: 5180
// Note you can make the accumulator into anything you want. That is, you can set the
// inital property of the accumulator to object or array and continously add things
// to it, to have the desired output.
// Other things that you can have "reduce" pass into your function is:
// accumulator, currentValue, currentIndex, array (yes the whole array)

view raw
ReduceInJS.js
hosted with ❤ by GitHub

FILTER

As in finding something based on a certain set of parameters. I think you guys kinda already know what this particular method does.

const transActionsForMike = [ {Name: "Bike", Cost: 5000},
{Name: "Apple Music", Cost: 20},
{Name: "Cook Book", Cost: 30},
{Name: "Azure Hosting", Cost: 60},
{Name: "Phone Bill", Cost: 70}];
// As seen in Reduce and Map, we can add more elements into the
// anonymous functions such as the index and the whole array
// filter gives us each element in the array. We then have to return
// "true" to keep it in, or "false" to get rid of it.
// In the case below we are keeping the element in the new array we are returning
// if it's cost property is less than 100 or more than 20
let MikesSmallTransactions = transActionsForMike.filter((ele) => {
return ele.Cost < 100 && ele.Cost > 20;
});
console.log(MikesSmallTransactions);
// MikesSmallTransactions is now: [ { Name: 'Cook Book', Cost: 30 },
// { Name: 'Azure Hosting', Cost: 60 },
// { Name: 'Phone Bill', Cost: 70 } ]

view raw
FilterInJS.js
hosted with ❤ by GitHub

I hope this helped you better understand Reduce, Map, and Filter 🙂

Django – Part 2

Intro

Django’s slogan is “The web framework for perfectionists with deadlines.” It accomplishes this in a few different ways, forced compartmentalization, built in development tools, and every feature you could ask for. Below we will discuss how to get started, and how see how Django handles MVC.

Getting started:

You first want to setup a virtual env. I am using Anaconda, so I would type in:

  1. conda create –name <your env name> django
  2. source activate <your env name>

Then you would use Django’s great command line tools to create your first project:

  • django-admin startproject <your app name>

Once you the command above you will have your very first Django app. However it won’t do very much. You can execute the following command to run the application:

  • python manage.py runserver

As you can see its pretty boring and does not due much. Django is built around the idea of applications, being different modules in your over all application. These modules are separate from the main project and encapsulate the different features of your application. You create a Django app by then running:

  • python manage.py startapp <app name>

By running the command you get a new directory generated in your folder structure.

Getting started with MVC (MTV):

Dajango does not use the MVC design pattern per say, rather it uses the MTV design pattern. MTV stands for:

M – model : This is a simple python classes.

from django.db import models
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic) # notice how easy it is to take care of foreign keys
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name

view raw
models_Django.py
hosted with ❤ by GitHub

As you can see it is very easy to start building the inter model relationships. All models need to inherit from the Model class. This is all possible due to Djangos built in ORM. The ORM abstracts away the whole concept of having to work with a SQL DB, since it also provides a easy method revise your tables to reflect changes to your python models. This is simply done by using the:

  • python manage.py migrate
  • python manage.py make migrations < Dajango app name>

T – template : This is your html that displays model data through server side rendering.

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8">
<title>Django Level Two</title>
<link rel="stylesheet" href="{% static "css/mystyle.css" %}"/>
</head>
<body>
<h1>YOLO LIFE</h1>
<h1>Here are your acces records</h1>
<div class="djangotwo">
{% if access_records %}
<table>
<thead>
<th>Site Name</th>
<th>Date Accessed</th>
</thead>
{% for acc in access_records %}
<tr>
<td>
{{ acc.name }}
</td>
<td>
{{ acc.date }}
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>NO ACCESS RECORDS FOUND</p>
{% endif %}
</div>
<img src="{% static "images/b.jpg" %}" alt="Uh Oh, didn't show !">
</body>
</html>

view raw
template_Django.html
hosted with ❤ by GitHub

Note that to serve these files, they need to be outside your main Django app, and they need to be reregistered in the Django settings file.

V – view : This is interestingly your controller.

from django.shortcuts import render
from django.http import HttpResponse
from first_app.models import Topic,Webpage,AccessRecord
# Create your views here.
def index(request):
webpages_list = AccessRecord.objects.order_by('date')
date_dict = {'access_records': webpages_list}
my_dict = {'insert_me':"This is coming from da Index.html!!!"}
return render(request,'first_app/index.html',context=date_dict)

view raw
view_Django.py
hosted with ❤ by GitHub

As you can see above, you tie the data from your controller to your view by way of dictionaries. And tie your templates to your controllers to your views by specifying the url path name, and the file name.

A point of interest here, is that unlike some other frameworks your mapping a url to a method, rather then a whole class that contains different methods. This method mapping to is done using url.py files that exist both in the directory of the main project and the django app.

The main project directory:

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from first_app import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^admin/', admin.site.urls),
url(r'^first_app/',include('first_app.urls')),
]

view raw
main_url.py
hosted with ❤ by GitHub

The Django app:

from django.conf.urls import url
from first_app import views
# is key word needs to be right
urlpatterns = [
url(r'^$',views.index, name='index'),
]

view raw
app_url.py
hosted with ❤ by GitHub

As you can see your using regex, to find a specific url, then mapping it to a method. The main urls.py file contains the main urls for the whole project and imports the urls specifically for the Django app. Whereas the Django app just contains the sub urls for that particular app.

The “http://127.0.0.1:8000/first_app&#8221; would hit the “first_app” app, then it would then hit any of the sub urls stored in the Django app urls file.

As you can see Django is not that hard use at all, and in most ways is significantly easier then other frameworks, that don’t have all these built in features. In the next blog post I will be discussing Models, the Django admin console, and how the ORM handles model changes.

You can find part one here.

 

Intro to Python ? – Part 1

Intro

You may have seen the title and been a bit surprised. In a previous post here, I said I don’t like Python. So you might be asking why I am even writing this. It’s cause I decided to give Python another shoot to wow me. Therefor I am going to start going into the cycle of learning a bit about it and then writing about it, and so on.

What is it ?

Its just a general purpose programming language.

What type of programming language is it really ?

It is a interpreted , dynamically typed, and strongly typed.

What can it do ?

Just like Java, C#, or C, it can do anything. That includes everything from Machine Learning to Desktop App Development.

What are it’s main selling points ?

  • Readable syntax to the point where, you can mistake it for pseudo code
  • Hugh and active community that supports it
  • Large selection of libraries
  • Large enterprises use it and actively contribute to it, such as Google, Reddit, The New York Times, and etc.

What are the draw backs ?

  • Its interpreted so it won’t be as fast as a compiled language
  • Far from the metal aka a thick layer of abstraction
  • No static typing
  • Object Oriented paradigm isn’t flushed out, for example there are no accesses modifiers on class variables (instance variables)
  • There are two different versions of language 2.7 and 3.x
    • Some libraries choose not to move to 3.x

 

MVC made easy

When I was first learning MVC I don’t have much to any experience programming for the web. I didn’t even now what the request response cycle was. The most programming experience I have ever had was printing interesting patterns using Java.

At the end of the day MVC is much more of an idea about how and why we should structure a program. For example when we write a web site that has your basic CRUD operations, you don’t want everything living in a single file that requires you to use the find functions to find your method.

So start separating out functionality, and at a very basic level we get a Model, View, and Controller. There for each of these things do something very specific. Most applications at a basic level usually involve:

  • Displaying data
  • Working with data
  • Navigation

The MVC design pattern helps you do those things, in a effect organized way. The direct translation would be:

  • Displaying data -> View : Think -> React, Angular, EJS
  • Working with data -> Model : Think -> Plain old classes (ORMs)
  • Navigation -> Controller : Think -> Express.js, Spring, Django

And there you have it, the MVC pattern explained. Now these direct translation might not be true for every framework out there, but for the most part they are true. You can this design pattern applied in almost every app frame work, form Metoer.js to ASP.Net MVC.

Note ORMs aren’t covered in this post, they require their own post to properly explain.

Hope that helped you guys understand.

OOP Explained

Preface

OOP is a way of thinking / design pattern. It can be understood by way of a number of different analogs. Not all the analogs described here are perfect but it makes some of the concepts easier to understand.

Blueprints:

Blueprints tell people how to make things, from your stove to your car. It has a clearly planned out way making sure everything works the way it is supposed to, and makes sure it satisfies it purpose.

You can think about “Classes” in the same way, expect what it builds is not something material, but an entity in computer. So if you wanted to make a car class you would thing about the things it should do. Such as accelerate, brake, turn on and off, open the door, and etc. Notice how all these things involve a verb , these actions that the car can take can be thought of as the methods in class. And then you have the stats of the care, such as the make, model, owner, and etc. These are all nouns and can be thought of as the variables of the classes.

There for when you instantiate a class, your telling the computer to build that objects using the guide (“Class”)

Collections of things:

People collect a lot of different things, from action figures, to stamps. These things all have common figures. Action figures are usually of a fictional character, are made of plastic, can be moved into different positions, and are usually a certain height .

And classes are the same, they hold variables and methods that come together since they are all kind of related. For example a coin classes could have a variable called “metal type” and a method called “flip”.

Cookie Cutters:

Cookie Cutters let you take cookie dough and make interestingly shaped cookies. Which is same thing as what a class does, except the cookie dough is your computers memory, and the cookie cutter is your class. Every time you instantiate a class,  your take some memory forcing it through the classes and making a object.