Create a JavaScript constructor function only if the types of parameters are verified

Imagine this scenario: I have a constructor function like the one below:

function Planet(solarSystem, habitable) {

    this.solarSystem = solarSystem;
    this.habitable = habitable;

}

Now, let's say after having a few too many beers, I try to create an instance of this constructor function with incorrect parameters:

let earth = new Planet(23, 'wooow');

Your task is to figure out how to set up a condition for creating the instance where it only happens if the parameter types are correct. If not, don't assign anything to earth.

Note: The expected parameter types for the Planet constructor function are Planet(String, boolean). Keep that in mind while solving this problem.

Answer №1

Here are a couple of ways to achieve it:

  • Simply return an object with no properties

    function Planet(solarSystem,habitable) {
        if (typeof solarSystem != 'string' && typeof habitable != 'boolean') {
           return Object.create(null);
        }
        this.solarSystem = solarSystem;
        this.habitable = habitable;
    }
    
    var planetObj1 = new Planet('TEST', true);
    console.log('planetObj1 ' , planetObj1 , 'is instanceof Planet', planetObj1 instanceof Planet);
    var planetObj2 = new Planet(14, 'TEST');
    console.log('planetObj2 ', planetObj2, 'is instanceof Planet', planetObj2  instanceof Planet);

  • If you need to return other JavaScript types like undefined or null, you can create a prototype to handle these cases

You have the option to create a prototype to determine whether to create your new object or not

function Planet(solarSystem,habitable) {

        this.solarSystem = solarSystem;
        this.habitable = habitable;

    }

    Planet.CreatePlanet = function(solarSystem, habitable) { 
        if (typeof solarSystem != 'string' && typeof habitable != 'boolean') return null;
        return new Planet(solarSystem, habitable);
    }

    // Instead of using new Planet():
    var obj = Planet.CreatePlanet(14, 'habitable');// This will return null
    console.log(obj);

Answer №2

To implement custom validation logic on an existing constructor, you can utilize a Proxy object in JavaScript:

function Galaxy(name, size) {
    this.name = name;
    this.size = size;
}

const validator = { // handler for Proxy
  construct: function(target, args) {
    let name, size;
    if (Array.isArray(args) && args.length === 2) {
      name = (typeof args[0] === 'string') ? args[0] : null;
      size = (typeof args[1] === 'number') ? args[1] : null;
      return ( name !== null && size !== null)
      ? { name, size} 
        : {}
    } else {
    return {} // return an empty object if arguments are not as expected
    }
  }
}

// create a new constructor with validation using Proxy
const validGalaxy = new Proxy(Galaxy, validator); 
// usage example: const milkyWay = new validGalaxy(<string>, <number>)

// demonstrate problematic behavior of the original constructor:

const andromeda = new Galaxy('Andromeda', 1000000);
console.log('andromeda (Galaxy): ', andromeda);

const invalid = new Galaxy('Invalid', 'large'); // using initial constructor, allowing wrong value
console.log('invalid (Galaxy): ', invalid);

// now apply validation with proxied constructor

const orion = new validGalaxy('Orion', 500000);
console.log('orion (validGalaxy): ', orion);

const failed = new validGalaxy('Failed', 'huge');
console.log('failed (validGalaxy): ', failed); // returns an empty object

If incorrect inputs are provided, the Proxy.construct method will always return an object instead of 'undefined'. This approach ensures consistent handling of input validation.

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

Angular sorting data is not functioning as expected

I've been attempting to utilize AngularJS to organize my data, but unfortunately, it seems to be ineffective. I am fetching data from Firebase () and using Node.js to transmit it to a controller. Controller Code var myApp = angular.module('myA ...

Ensuring uniform sizing of anchor text using jQuery

My goal is to creatively adjust the font size of anchor text within a paragraph, making it appear as though the text is moving towards and away from the viewer without affecting the surrounding paragraph text. Currently, I am encountering an issue where th ...

Why is my Angular router displaying the page twice in the browser window?

Angular was initially loading the page on the default port localhost:4200. I wanted it to serve as localhost:4200/specialtyquestions when the app builds, and that is working, but the pages are appearing twice in the browser. Any ideas on what might have be ...

What is the best way to send a 2D array from JavaScript to PHP?

Currently, I am immersed in a school project that requires the extraction of product data from numerous online retailers by utilizing diverse APIs/AJAX calls. Subsequently, I need to organize this data in PHP, employing an AJAX call for each individual r ...

Displaying spinner until the entire section has finished loading

In order to display a loading spinner until all images in a specific section of the page have fully loaded, I am utilizing Django, jQuery, and Ajax technologies. The HTML structure consists of two main divs: On the left side, there is a table, while on t ...

Steps for implementing a single proxy in JavaScript AJAX with SOAP, mirroring the functionality of the WCF Test Client

I am working with a WCF web Service and a javascript client that connects to this service via AJAX using SOAP 1.2. My goal is to pass a parameter to instruct the AJAX SOAP call to use only one proxy, similar to how it is done in the WCF Test Client by unch ...

Calling Ajax to Flask for fetching MySQL query results

My goal is to populate a drop-down list in my HTML using AJAX by calling my flask app app.py from app.js. I am attempting to load the data when the page initially loads and triggering the AJAX within $(document).ready as shown below: Here is the content o ...

Utilizing Shopify API to seamlessly add items to cart without any redirection for a smoother shopping experience

Looking for a solution to submit an add to cart POST request without any redirection at all? I have tried changing return_to to "back" but that still reloads the page, which is not ideal. My goal is to smoothly add the item to the cart and notify the cli ...

iterative string ng-list that is specified in the text $scope variable

Is there a way to set up a dynamic ng-repeat in $scope variable that looks like this: $scope.radioOptions =[{value:1,name:'radio1'},{value:2,name:'radio2'}]; $scope.item = { model: "radio", radioOptions:'opt in radioOptio ...

Converting user input from a string to an object in JavaScript: a comprehensive guide

Is there a way to transform user input string into objects when given an array of strings? ["code:213123", "code:213123", "code:213123"] I am looking to convert this array into an array of objects with the following format: [{code: "213123"},...] ...

The VueJS component from a third-party source is not located in the node_modules directory

Utilizing vue-cli version 3 for a fresh vuejs project (I've been dedicating ample time to learning vuejs, but this marks my initial attempt at integrating a third-party component). I'm aiming to incorporate a visually appealing grid component. Th ...

What is the reason for the unusual incrementing of the index in JavaScript?

When running this code snippet, the first console log correctly shows 0. However, the second console log displays 1. Why is the index being incremented before the loop has ended? for (var i = 0; i < this.offlineTimeSlots.length; i++) { con ...

How can I add an item to an array within another array in MongoDB?

I currently have a Mongoose Schema setup as follows: const UserSchema = new mongoose.Schema({ mail: { type: String, required: true }, password: { type: String, required: true }, folders: [ { folderName: { type: S ...

Converting a JavaScript array to a PHP array using POST request

In my JavaScript script, I have the following code: cats = []; cats.push(cat1); cats.push(cat2); $.post( URL+"/edit-article.php", { id: artId, title: "PZujF0 wxKLCW", content: "ILEn3o oU9Ft6oU5", author: author, cat_id: cats } ).done(function( data2 ) ...

What is the best way to create an array within an object in JavaScript?

Here is the code snippet I'm working with: var Memory ={ personAbove: "someone", words: wordsMem = [] <<<<<this part is not functioning properly } I need help figuring out how to make it function correctly. Specific ...

Can the useNavigation hook be used to navigate to a class component in React?

How can I use the useNavigation hook to navigate to a class component? Here is my class: export default class AzureLogin extends React.Component I want to navigate to AzureLogin from Screen1. What is the correct way to achieve this? import { useNavigati ...

Creating an Engaging Data Visualization: Blending Candlestick Insights with Line Graphs

I'm attempting to display a moving average on a candlestick chart, but I'm facing an issue where the path of the line is not fully appearing on the SVG canvas that I've created. I've searched through various posts to understand how to o ...

Explore the Wikipedia API play area by searching based on the user's input

Having trouble searching Wikipedia based on user input. Initially, I suspected a cross-domain issue, but I believe .ajax should resolve that. You can view the codepen here: http://codepen.io/ekilja01/pen/pRerpb Below is my HTML: <script src="https:// ...

Trouble encountered while attempting to install ng2-bootstrap within my Angular 2 project

I've been attempting to integrate ng-bootstrap into my Angular 2 application for dropdown functionality. However, I'm encountering the following error in the console: Console error Here is the snippet of my System.config.js code: System.config. ...

Looking for a way to choose a button with a specific class name and a distinct "name" attribute using jquery?

I am currently working on developing a comment system. As part of this system, I want to include a toggle replies button when a user posts a reply to a comment. However, I only want this button to be displayed if there are no existing replies to the commen ...