Finding it difficult to differentiate shapes based on the number of sides

Seeking to identify the type of shape based on the number of sides passed in. The code provided only recognizes the first index, which is a triangle. I suspect this is because I am not correctly comparing the number of sides to the sides property in the array. I attempted to use filter, forEach, and map methods but got stuck. I appreciate any assistance.

var Shape = function(sides) {
  this.sides = sides;

  if (this.sides < 3 || typeof(this.sides) !== 'number'){
    this.sides = null;
  }
};
Shape.prototype.getType = function(sides){
  var shapes = [{type: "triangle", sides: 3}, {type: "quadrilateral", sides: 4}, {type: "pentagon", sides: 5}, {type: "hexagon", sides:6}, {type: "heptagon", sides: 7}, {type: "octagon", sides: 8}, {type: "nonagon", sides: 9}, {type: "decagon", sides: 10}];

  for (var i = 0; i < shapes.length; i++){
    console.log(shapes[i].sides);
    var sideExists = shapes.indexOf(shapes[i].sides) > -1;
    if (sides === sideExists){
      return shapes[i].type;
    }else{
      return 'Could not determine type';
    }
  }
};

Answer №1

If given the choice, I would opt for approaching it in this manner.

var Polygon = function(sides) {
  (sides < 3 || typeof sides !== 'number') ? this.sides = 0 : this.sides = Math.floor(sides);
};

Polygon.prototype.getName = function(){
  var polygons = {0: "not defined polygon", 3: "triangle", 4: "quadrilateral", 5: "pentagon", 6: "hexagon", 7: "heptagon", 8: "octagon", 9: "nonagon", 10: "decagon"};
  return polygons[this.sides];
}

var hexagon = new Polygon(7);
document.write("<pre> I belong to the shape of " + hexagon.getName() + "</pre>");

Answer №2

To properly compare the sides parameter with the sides in the shapes array, the loop should be modified as follows:

Shape.prototype.getType = function(sides){
  var shapes = [{type: "triangle", sides: 3}, {type: "quadrilateral", sides: 4}, {type: "pentagon", sides: 5}, {type: "hexagon", sides:6}, {type: "heptagon", sides: 7}, {type: "octagon", sides: 8}, {type: "nonagon", sides: 9}, {type: "decagon", sides: 10}];

  for (var i = 0; i < shapes.length; i++){

    if (sides === shapes[i].sides){
      return shapes[i].type;
    }
  }

  return 'Unable to determine type';
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Three.js to showcase large 3D images from a JSON file

I am in need of showcasing 3D images. I have a .obj file that is 80 MB in size which I converted to a json file size of nearly 75 MB. While using three js, I managed to display a rotating 3D image, but the main issue is the loading speed, which currently t ...

Error in linking PHP code to display stored tweets using HTML code

![enter image description here][1]![image of output of twitter_display.php][2] //htmlsearch.html file <!doctype html> <html> <head> <title>Twitter</title> <meta charset="utf-8"> <script> window.onload = function ...

I am encountering an issue with this code. The objective is to determine the frequency at which a specific word appears in the provided paragraph

function processWords(){ text = document.getElementById("inputText").value; text = text.replace(/(^\s*)|(\s*$)/gi,""); text = text.replace(/[ ]{2,}/gi," "); text = text.replace(/\n /,"&bso ...

The Mongoose connection keeps failing to reconnect and maintain a stable heartbeat

I am facing an issue with the automatic reconnection feature in mongoose on my project. Despite configuring it to reconnect after a certain interval, it does not work as expected. Even if the credentials are correct, mongoose should attempt to log in perio ...

Ways to verify if one div in jQuery contains identical text to another div

I need help with a jQuery script to remove duplicate text in div elements Here's the requirement: If div1 contains the text "hi" and div2 also contains "hi", then div2 should be removed Below is my current code snippet: <script src="https:/ ...

Obtain the details of a selected item in a list by tapping on it using Natives

I am wondering how to retrieve the context of a tapped item in a listview. For example, if there are three items in the list, how can I determine that the second item was clicked and access the data related to that item in the observable array? For instan ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

Media queries in JavaScript allow developers to adjust the styling

I'm facing an issue with reducing the size of a cube on smaller screens using media queries. I have implemented media queries in JavaScript because my cube size is defined in JS. However, the cube size remains the same even when I resize the browser w ...

Testing Your Angular 7 Code: Unit Testing Made Easy

I am currently working on developing unit tests for this angular script: export class DataService { private csrfToken: string = ''; private isContentShown: BehaviorSubject<boolean> = new BehaviorSubject(true); constructor(private h ...

The connection was refused by hapi.js

We have recently encountered an issue while using hapijs: hapi, {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","domainEmitter":{"domain":{"domain":null,"_events":{},"_maxListeners":10,"members":[]},"_events":{},"_maxListeners":10},"doma ...

Guide to sending an array to Jade for rendering using NodeJS and ExpressJS

Coming from a background in "functional" programming languages like PHP, Lua, and C, I am currently facing a challenging learning curve as I transition to the MVC model used in NodeJS. I've been struggling to display a simple MySQL array in Jade and ...

Holding off $ajax requests until specific code finishes executing

I'm facing an issue with incorporating geolocation data into my $ajax call URL. Currently, both console.log(lat/lon) calls return the initial value of 0, indicating that the geolocation call is too late to provide the updated values. This results in t ...

What options do I have for sorting through my inventory using the search feature?

Having some trouble setting up isotope filtering on my search bar. I have managed to get the Isotope function working on checkboxes, but for some reason, my search bar isn't functioning as expected. I found a solution online for filtering results bas ...

Canvas cannot be duplicated due to tainting, html2canvas

I have encountered an issue with my Snapshot button in HTML. Despite trying to add crossorigin="anonymous" to my script, I am still facing the problem of a Tainted Canvas when clicking the button. The button function is as follows: $('#snap').cli ...

A guide to seamlessly adding calendar events with JSON data using the powerful Ionic Native Calendar Plugin

Hello there, I am in the process of developing an Ionic app and incorporating the Ionic Native Calendar plugin. My goal is to utilize this plugin to dynamically adjust the calendar event parameters through JSON linked to a Firebase database, rather than h ...

What could be causing the issue of messages not displaying while incorporating connect-flash with res.locals in express.js and ejs templating?

Here are some snippets of code that may be useful. Connect-flash is designed to display messages on test1 and test2, but there seems to be an issue with displaying messages for test 3: user registration when all three tests are redirected to the same &apos ...

Is there a solution to rectify the error related to POST net::ERR_CONNECTION_REFUSED?

Every time I try to post via ajax, an error keeps popping up. Here are the snippets of my code: let xhr = new XMLHttpRequest() let data ={ "name": "test", "phone": "12345678", "email": &qu ...

Subset a 2-dimensional array by row to only include rows with a particular value

My goal is to subset 2D arrays of varying dimensions and extract only the columns that contain a 3 using the "any" function. While it works well with multiple columns containing a 3, it fails when there is only one or zero columns with a 3 present. Here&ap ...

Enter an URL and click the submission button

I'm currently working on a bookmarklet that can grab the URL of the page the user is on, insert that URL into a text field on a specific form, and then automatically submit the form. Here is the code I have so far. It successfully captures the curren ...