Showing posts with label Javascript tricks. Show all posts
Showing posts with label Javascript tricks. Show all posts

Wednesday, July 11, 2018

[JAVASCRIPT] Binary Search Tree, Overloading prototype and implementing a map function

BST - Binary Search Tree

Hello, today I will show you how to develop the binary tree class and how to add a map method, along with the other common methods. We use the map method very frequently with JS Arrays. So I thought we can add it to the BST class we create. 

What is the map method?

The JS Array provides many intersting methods, that take as parameter a function and apply it over the data. We have map, filter etc. which are very useful for Array mutation.
Let us see the map method in action:

Consider this code snippet

var vals = [5, 6, 7, 8];
vals.map(val => val = val * val);

So what is the output ?

console.log(vals);

// You get [25, 36, 49, 64]

Do you see what happened?

val => val = val * val;

Breaking it down,

for every val in vals{
    val = val * val;
} //Not actual JS syntax


So we just saved ourselves from writing the for loop. And since this map function takes a function as a parameter, we can mutate the array however we need to.

I personally am trying to make this post a little easier to comprehend as I too was really confused with the syntax of JS and usage of => , but now I know to use it well and it helps me arrive at solutions much quicker. Filter works in a similar manner.

Now let us get our hands dirty with the code for BSTs:

First we need the Node class, defined by this function.

function Node(val){
  this.val = val;
  this.left = null;
  this.right = null;
}

Next we need the BST class, defined like so.

function BinSearchTree(){
  this.root = null;
}

Next, we overload all the functions we need like so.

push to add values to the BST

BinSearchTree.prototype.push = (val) => {
  var root = this.root;
  if(!root){
    this.root = new Node(val);
    return;
  }
  var currentNode = root;
  var newNode = new Node(val);
  while(currentNode){
    if(val < currentNode.val){
      if(!currentNode.left){
        currentNode.left = newNode;
        break;
      }
      else{
        currentNode = currentNode.left;
      }
    }
    else{
      if(!currentNode.right){
        currentNode.right = newNode;
        break;
      }
      else{
        currentNode = currentNode.right;
      }
    }
  }
}

toString using in-order traversal.

BinSearchTree.prototype.toString = () =>{
  var cur = this.root;
  var s = [];
  var done = false;
  while(!done){
    if(cur){
      s.push(cur);
      cur = cur.left;
    }
    else{
      if(s.length > 0){
        cur = s.pop();
        console.log(cur.val);
        cur = cur.right;
      }
      else{
        done = true;
      }
    }
  }
}


find to search for a key element

BinSearchTree.prototype.find = (key) =>{
  var cur = this.root;
  var s = [];
  while(1){
    if(cur){
      s.push(cur);
      cur = cur.left;
    }
    else{
      if(s.length > 0){
        cur = s.pop();
        if(cur.val == key){
          return true;
        }
        cur = cur.right;
      }
      else{
        return false;
      }
    }
  }
}

map applies a function over the array extended to BST

BinSearchTree.prototype.map = (d) =>{
  var cur = this.root;
  var s = [];
  var done = false;
  while(!done){
    if(cur){
      s.push(cur);
      cur = cur.left;
    }
    else{
      if(s.length > 0){
        cur = s.pop();
        cur.val = d(cur.val);
        cur = cur.right;
      }
      else{
        done = true;
      }
    }
  }
}


So these are the methods I developed. If you notice, the methods have a very similar structure with minor changes to the core operation. If you have any comments, please be sure to leave them below!

Here is some starter code to test the Implementation.

var bst = new BinSearchTree();
for(let i=0; i < 10; i ++){
  bst.push(parseInt(Math.random()*10));
}
bst.toString();

console.log(bst.map(x => x = x* x));
bst.toString();

Wednesday, April 4, 2018

$No_Code 2 var C0D3R Pt1

Coding coding coding.
Everyone wants to know about it.
Some get it, some don't. 
I for one always knew that I was going to be a computer programmer.

Ever since my school days, I have wondered how those amazing games (EA: Need for Speed series, etc.) worked in the background. I thought about graphics that went into them, learnt about game development, and web development.

I just had the highest level of curiosity for cool things. I always loved reverse engineering stuff, taking things apart and figuring out step by step how to put it back together. Such interest has propelled me to reverse engineer many real-world objects, and at a novice level many games, websites and mobile apps. It is just so interesting to figure something out and generate new ideas from that newfound theory.

Hence, I spent most of my days doing things like web development, gaming, and coding. I picked up languages one by one. Now I know so many I cannot even keep track of half of what I know and what I remember. But just know one thing, one must always know what kind of programming languages he can use to get the required results.

Now, this comes with practice. However, you must continue to try to reverse engineer and learn new things every day. Only then can you catch up with the current trends right?

There are few approaches I would like to suggest people who wish to be good developers:

  • Always write logically and syntactically correct code. i.e. Don't waste time on silly things like syntax and logic.
  • Code formatting and documentation is an indirect marketable skill. Clear, readable, understandable code is the dream of many Tech team leads. When you write code, be sure to make it readable and formatted well. Always include very meaningful variable names, supporting documentation, using comments, etc. This helps anyone who reads your code to understand exactly what is happening and they can pick up where you left off, as it is very unlikely you will work single-handedly on any project.
  • Try to understand the underlying differences in approaches while using various different languages.
  • When writing code, keep in mind:
    • Keep unnecessary steps to a minimum,
    • Iteratively make your algorithm better,
    • Only generate it into production code when the algorithm seems to be at its best,
    • Try to come back after a while to check on the algorithm once more. Usually, you'll find incredibly stupid/silly things that can be fixed or updated. Hence, point 1.
    • Keep the number of lines of code to a minimum, per function. A function/method should only perform one task. Example: function makePizza() needn't worry about delivering it.
  • Look into coding challenges online on the tens of hundreds of platforms such as HackerRank, GeeksForGeeks, etc. Solve one a day at the least.
  • Work on different IDEs, online and offline. 
  • Try to find the balance between designing and developing.
  • You are bound to fail, just don't give up. Programs will work only at the last hour before deadlines. Such is many people's fate.
I have spent hours and hours on a single step or single problem, only to realize next day what I missed. It can happen to anyone. You could also find it difficult to read and understand even standard code or others' code. 

Tricks:

  1. Learn & develop in multiple languages simultaneously. It gives a better level of control over your emotions as a programmer.
  2. Write the same program in different languages.
  3. Decide before you begin exactly what your stack is going to be. (see below for stacks)
  4. Be willing to spend the rest of your life in front of a computer in the worst case. Further, get ready to spend more than 12-14 hrs a day, <coding>
  5. Choose the latest stack, and do company specific stack building.

Stacks:

  • Stacks are groups of technologies/libraries or frameworks, which are used to build a specific application.
  • There are many ways to categorize them. I will categorize them broadly using:
    • Ease of Learning
      • MEAN, python Django, .NET+web, JAVA(core/enterprise)
    • Productivity
      • Racket, Scheme, Lisp, - Almost ready for anything
      • Python - numpy, scipy, sklearn, serial, pygame etc.
      • C/C++ - Windows, Linux, Systems Programming, OpenGL, GameDev
      • JAVA - CORE/EE Powerful enough to run anywhere, anything.
    • Type of application
      • Web: Frontend +PHP, NodeJs, Ruby, etc. Where Frontend can be AngularJs, ReactJs, etc.
      • Mobile: AndroidSDK, IOS_Swift, etc, React-native, IconicFramework/Cordova, AngularJS etc.
      • Dekstop: C/C++, JAVA, python, etc.
Computer Architecture/How it works basics (can skip):
  1. Fact - Computers are dumb until made smarter by equipping them with Human-based intelligence.
  2. Computers can only understand 0/1, Binary.
  3. Steps for programs to run on the CPU:
    • A program is written in a high-level language
    • Compile means it is converted to assembly and optimized as best as can to run faster. 
    • The compiled program can then be converted further to binary in the linking step.
    • Further optimizations are done.
    • Finally, the program is assigned a position in the CPU running queue.
  4. Next?
    • The CPU contains certain architecture to make the program have its own space and allow it to work from there.
    • This architecture is called the Stack. The CPU consists of closely bound elements such as the Stack, Registers, and Cache.
    • The Main memory is the next fastest. The Secondary memory, (DISK) is the slowest. hence, one should try to load chunks of working data into the main memory or the cache to have the fastest processing speed.
    • So basically, when the assembly program arrives, the CPU assigns certain stack space for each such program. The variables that are found to be alive are sorted into registers when they appear in the code. These registers are the only ones who can operate on data. We all know that most of the worlds most complex problems can be reduced to simple mathematical equations. This is one of the main reasons that the CPU is hooked up to the ALU- Arithmetic and Logic Unit. There is a whole book on this topic Computer Architecture, but mainly, each program becomes a function for the CPU. Most functions are reduced to math or logic operations completed by ALU. If there is a store/read command, then the memory is accessed and the registers are updated.
    • This process of CPU is so repeated in every aspect of programming. If we have large data, we divide and conquer. If we need fast processing, we try to place most of the required files into the same working directory (example: external js libs vs local js lib files downloaded ahead of time)
  5. Now, you don't need to get into any of this. From programmers standpoint always remember one thing. Answer these questions:
    1. What's the output?
    2. What's the input?
    3. Can I code it?
      • What do I need?
      • What do I have?
      • Where do I get other dependencies? Can I get them?
    4. Choose the language
Feel free the leave comments, or contact me personally on my Gmail. I am willing to provide one-on-one training on any technology I'm comfortable with. Be sure to ask!






Friday, March 30, 2018

Web effects, HTML, Jquery, CSS Part 1.1 - My code for my front page.

Front page animation Sam's Playground (Portfolio)

Code Snippet for my animation on my front page here

Javascript

So first we start by defining a few variables. Next we extract the characters from the head tag and perform required steps in the extract function. This is a function I defined to perform animation. It is a helper function. Also, we register animation frame for the window. All happening inside the ready function.

var head1 = $("h1#head1");
var total = 0;
var scene;
var camera;
var renderer;
var mwidth = 900, mheight = 900;
// Jquery Ready function, triggered when document is "ready"
$(document).ready(function() {
//Extract the head tag value
extract(head1);
// Use built-in function to create new animation frame to make it smooth.
window.requestAnimFrame(dripp);
// Variable to store oldtext from head value.
var oldtxt;
});


// Extracting Characters from the string from head tag. Making this a slightly modular approach.
function extract(_textholder){
var htext = _textholder.text();
var hlen = htext.length;
total += hlen;
_textholder.text("");
for(i=0; i< hlen; i++){
_textholder.append("<h1
class='drippers'>"+htext[i]+"</h1>");
}
}
// Function that actually performs addition and deletion of animation class so that we can animate random characters.

function dripp(){
rnd = parseInt(Math.random() * total);
$(".drippers").each(function(i, obj) {
if(i == rnd)
$(this).toggleClass("drippin");
});
window.requestAnimFrame(dripp);
}

// Fix for built-in function for setting callback time.
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000);
};
})();

CSS

.drippin is a CSS class which enables the 'drippin' keyframe animation. This is the class we apply and remove to perform the animation. The animation itself is defined in keyframes. The first part of the animation starts at 0% and the text-shadow property allows to create the effect. We define the property value for each of the time steps in the keyframe. We define individual keyframe animations for each browser.
Chrome - @-webkit-keyframe
Mozilla - @-moz-keyframe
Opera - @-o-keyframe
Others - @keyframe

.drippin {
 -webkit-animation: ease drippin 1.5s infinite;
 /* Safari 4+ */
 -moz-animation: ease drippin 1.5s infinite;
 /* Fx 5+ */
 -o-animation: ease drippin 1.5s infinite;
 /* Opera 12+ */
 animation: ease drippin 1.5s infinite;
 /* IE 10+, Fx 29+ */
}
.drippers {
 text-transform: full-width;
}


@-webkit-keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px black;
 }
 10% {
  text-shadow: 0px -0px 2px red;
 }
 15% {
  text-shadow: 0px -3px 3px red;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -10px 4px white;
 }
}
@-moz-keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px red;
 }
 10% {
  text-shadow: 0px -0px 2px red;
 }
 15% {
  text-shadow: 0px -3px 3px red;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -100px 4px maroon;
 }
}
@-o-keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px red;
 }
 10% {
  text-shadow: 0px -0px 2px red;
 }
 15% {
  text-shadow: 0px -3px 3px red;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -100px 4px maroon;
 }
}
@keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px blue;
 }
 10% {
  text-shadow: 0px -0px 2px lightgreen;
 }
 15% {
  text-shadow: 0px -3px 3px blue;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -100px 4px lightgreen;
 }
}

If any of the code doesn't work, you can troubleshoot it by:

  1. Checking the variable names, definitions, and other related syntax 
  2. Remove all or misplaced comments.
  3. Check for keyword spelling mistakes.
  4. Try a different browser.
  5. Open Inspector > Console to check for errors.

Best of luck, and happy coding! Hope you have fun and create more such animations to place on your websites!

Samartha  K V