Creating 3 Stacks With 1 Array in JavaScript

Creating 3 Stacks With 1 Array in JavaScript

In this article, you'll learn how to create 3 Stacks with 1 Array in JavaScript

What Is A Stack?

A stack is a data structure that is based on the concept of “last-in-first-out” or “LIFO.” You can think of it like a stack of books where the top book has to be taken off the stack before you can retrieve the bottom book. JavaScript doesn’t have a native stack data structure, so we’re going to create one today.

Our array will contain three different stacks of a fixed size. The top of the stack will be on the right side and the bottom of the stack will be on the left side. You can picture it similar to this diagram. If this stack was full, the bottom element would live at stack[0] and the top element would live at stack[stack.length-1].

Class Breakdown

Our stacks will have a fixed size which will be equal to the argument passed in at instantiation.

Properties

The following properties will be initialized within the constructor:

  • _stackCapacity: The maximum number of elements that can fit into one stack. This is a read-only property which is why it’s prepended with an underscore.
  • values: An array which contains of all elements in the three stacks
  • sizes: An array with three indices, each representing the current number of elements in the respective stacks.
  • numberOfStacks: A constant which represents the total number of stacks we’ll allow our array to hold. We’re initializing this to three, however future iterations of this MultiStack class could take in a second argument to customize the number of stacks the array can hold.

Methods

Our MultiStack class will contain the following methods:

  • get stackCapacity(): Returns the total capacity of each of the stacks (this is just a way for me to check that everything is working as expected, we won’t really be using this.)
  • push(stackNumber, value): Pushes the value onto the top of the respective stack number.
  • pop(stackNumber): Pops the top item off of the respective stack number.
  • peek(stackNumber): Returns the top item off of the respective stack number. It’s just a way for us to “peek” at what element is on the top; no stack mutation will happen.
  • isEmpty(stackNumber): Returns a boolean which indicates whether the respective stack has values.
  • isFull(stackNumber): Returns a boolean which indicates whether the respective stack is full.
  • indexOfTop(stackNumber): A helper method which returns the index, in the values array, of the top element in the respective stack.

Constructor

The first thing we’ll do is create our constructor. It will take in one argument, the stack size. Thus, the total length of our values array will be 3 * the stack size (since we’re initializing numberOfStacks to three).

We will initialize the sizes array to contain three indices with the value zero. For our purposes we will assume that the values being pushed onto the stacks are positive integers. You can change this logic to fit your needs.

class MultiStack {
  constructor(stackSize) {
    this._stackCapacity = stackSize;
    this.values = [];
    this.sizes = [0, 0, 0];
    this.numberOfStacks = 3;
  }
}

Get Stack Capacity

This method returns the total capacity of each of the stacks (this is just a way for me to check that everything is working as expected, we won’t really be using this.)

You can read more about JavaScript getters on MDN.

get stackCapacity() {
  return this._stackCapacity;
}

isFull

This method returns a boolean which indicates whether the respective stack is full. It will check how many elements are currently on the respective stack and compare it against the stack capacity.

isFull(stackNumber) {
    return this.sizes[stackNumber] === this._stackCapacity;
}

isEmpty

This method returns a boolean which indicates whether the respective stack has values.

isEmpty(stackNumber) {
  return this.sizes[stackNumber] === 0;
}

indexOfTop

This is a helper method which returns the index, in the values array, of the top element in the respective stack.

This explanation could get a little tricky, so stick with it! I’ve included diagrams to better visualize the process.

First we need to grab the offset of the stack within the values array. To do this, we’ll multiply the stack number we want by the capacity of each stack.

For example, let’s find the index of the top item in stack 2 given that the _stackCapacity for each stack is 5. The stacks contain the following elements:

  • Stack 0: [1, 12]
  • Stack 1: [18, 8, 2]
  • Stack 2: [5, 9, 66, 15]

Here is a visual representation of what the values array looks like:

Step 1: Calculate the offset; find the index of the bottom item in stack two

Assuming our stacks start at zero (i.e. stack 0, stack 1, stack 2), we can find where the bottom of stack two starts in the values array by multiplying the stack we’re looking for, two, by the stack capacity, which is the value passed in at instantiation. If our stack capacity is five, we know that the bottom element of stack two starts at index 10 in the values array.

index of bottom element in stack 2 = stack we’re looking for * capacity of each stack.

index of bottom element in stack 2 = 2 * 5 (found from <em>_stackCapacity</em>)

index of bottom element in stack 2 = 10.

Step 2: Calculate the total number of values currently in stack two

We already know how many values are in stack 2; they’re being kept in the sizes array. So by grabbing the value of sizes[2] we know how many elements are in stack 2: 4

Step 3: Add the offset with the total number of values in the stack, minus one

We have to subtract one from the number of items in the stack, since our array starts at index zero.

When we add it all up we get:

index of top element in stack 2 = offset + number of values in stack two— 1

index of top element in stack 2 = 10 + 4 — 1

index of top element in stack 2 = 13

The code for this is as follows:

indexOfTop(stackNumber) {
  const offset = stackNumber * this._stackCapacity; // Find the starting point in the array
  const size = this.sizes[stackNumber]; // How many elements are in that stack currently?
  return offset + size - 1;
}

Push

The push method pushes a value onto the top of the respective stack. It takes in two arguments:

  • The stack to push the value onto
  • The value
  1. The first thing we have to do is check whether the stack is full. If it is full, let’s console.log the message Stack number ${stackNumber} is full.

  2. If the stack isn’t full, increase the number of items in the stack, which is found in the sizes array.

  3. Then add the new value to the top of the stack. We’ll use the indexOfTopmethod we just explained above to grab the top of the stack and add a value on top of it.

  4. If it’s successfully added, let’s console.log a friendly message.

push(stackNumber, value) {
  if (this.isFull(stackNumber)) {
    return console.log(`Stack number ${stackNumber} is full`);
  }
  // Add one to the respective stack count
  this.sizes[stackNumber]++;
  // Add the value to the list
  this.values[this.indexOfTop(stackNumber)] = value;
  return console.log(`Item ${value} has been successfully added to stack ${stackNumber}`);
}

Pop

This method pops the top item off of the respective stack number. It takes in one argument:

  • The stack to pop the value off of
  1. We must first check if the stack is empty using the isEmpty method. If it is, we’ll return a console.log a message.
  2. If the stack isn’t empty, we’ll grab the index of the top element on the stack using the indexOfTop method and save it to a variable called topIndex.
  3. Now let’s grab the value of that element. We can do this with this.values[topIndex] . We’ll return this element, which is why we need to save it to a variable.
  4. We also need to tell the values array that the value at this index no longer exists. We’ll set this explicitly to zero (this could pose issues if your stack can take zero as a value, but for our sake we’ll assume the stack only accepts positive integers).
  5. We must also decrement the size of the stack in the sizes array. We can do this with this.sizes[stackNumber]--.
  6. Finally, let’s return the value we just popped off.
pop(stackNumber) {
  if (this.isEmpty(stackNumber)) {
    return console.log(`Stack number ${stackNumber} is empty`);
  }
  const topIndex = this.indexOfTop(stackNumber);
  const value = this.values[topIndex];
  this.values[topIndex] = 0; // Clear out element
  this.sizes[stackNumber]--; // Reduce num elements in the stack
  return value;
}

Peek

This method returns the top item off of the respective stack number. It doesn’t alter the stack, it simply lets you view the element on the top. It takes in one argument:

  • The stack whose top value we want to peek at
  1. We first have to check if the stack is empty. We can use the isEmptymethod to do so. If it is empty, let’s console.log a friendly message.
  2. If the stack isn’t empty, we need to find the index for the element on top of the stack. We can use the indexOfTop method to do so.
  3. Finally, we can return the value found at that index with this.values[topIndex] .
peek(stackNumber) {
  if (this.isEmpty(stackNumber)) {
    console.log(`Stack number ${stackNumber} is empty`);
  }
  const topIndex = this.indexOfTop(stackNumber);
  return this.values[topIndex];
}

Putting It All Together

The final class looks like this:

class MultiStack {
  constructor(stackSize) {
    this._stackCapacity = stackSize;
    this.values = []; // values in the stack which is max size of stackSize * 3
    this.sizes = [0,0,0]; // length of 3 and each index contains the number of items in the respective stack
    this.numberOfStacks = 3;
  }
  
  get stackCapacity() {
    return this._stackCapacity;
  }
  
  push(stackNumber, value) {
    if (this.isFull(stackNumber)) {
      return console.log(`Stack number ${stackNumber} is full`);
    }
    // Add one to the respective stack count
    this.sizes[stackNumber]++;
    // Add the value to the list
    this.values[this.indexOfTop(stackNumber)] = value;
    return console.log(`Item ${value} has been successfully added to stack ${stackNumber}`);
  }
  
  pop(stackNumber) {
    if (this.isEmpty(stackNumber)) {
      return console.log(`Stack number ${stackNumber} is empty`);
    }
    const topIndex = this.indexOfTop(stackNumber);
    const value = this.values[topIndex];
    this.values[topIndex] = 0; // Clear out element
    this.sizes[stackNumber]--; // Reduce num elements in the stack
    return value;
  }
  
  peek(stackNumber) {
    if (this.isEmpty(stackNumber)) {
      console.log(`Stack number ${stackNumber} is empty`);
    }
    const topIndex = this.indexOfTop(stackNumber);
    return this.values[topIndex];
  }
  
  isEmpty(stackNumber) {
    return this.sizes[stackNumber] === 0;
  }
  
  isFull(stackNumber) {
    return this.sizes[stackNumber] === this._stackCapacity;
  }
  
  indexOfTop(stackNumber) {
    const offset = stackNumber * this._stackCapacity; // Find the starting point in the array
    const size = this.sizes[stackNumber]; // How many elements are in that stack currently?
    return offset + size - 1;
  }
}

You’ve now created an array that represents three fixed-size stacks! You can view the CodePen for this class here.

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

7 Best Javascript Iframe Libraries

7 Best Javascript Iframe Libraries

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

1. Zoid

A cross-domain component toolkit, supporting:

  • Render an iframe or popup on a different domain, and pass down props, including objects and functions
  • Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions
  • Create and expose components to share functionality from your site to others!
  • Render your component directly as a React, Vue or Angular component!
    It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups!

Download


2. Postmate

Postmate is a promise-based API built on postMessage. It allows a parent page to speak with a child iFrame across origins with minimal effort.

Download


3. Iframe Resizer

Keep same and cross domain iFrames sized to their content with support for window/content resizing, in page links, nesting and multiple iFrames

Demo

Download


4. Iframely

Embed proxy. Supports over 1800 domains via custom parsers, oEmbed, Twitter Cards and Open Graph

Demo

Download


5. React Frame component

This component allows you to encapsulate your entire React application or per component in an iFrame.

Demo

Download


6. Seamless.js

A seamless iframe makes it so that visitors are unable to distinguish between content within the iframe and content beside the iframe. Seamless.js is a JavaScript library (with no dependencies) that makes working with iframes easy by doing all the seamless stuff for you automatically.

Demo

Download


7. Porthole

A proxy to safely communicate to cross-domain iframes in javascript

Demo

Download


Thank for read!