Retrieve parameters from functions and convert them into coherent statements

As I delved into the world of THREE.js, I experimented with various geometries. However, manually writing out each geometry became tedious due to the vast array of options available.

For example, creating a simple cube required these lines of code:

var material = new THREE.MeshNormalMaterial();
var boxGeometry = new THREE.BoxGeometry( 20, 20, 20 );
var box = new THREE.Mesh( boxGeometry, material );
box.position.set(-10, -10, 0);
scene.add( box );

If I wanted to add another shape like a cone, I would have to mindlessly copy and paste the above lines, only replacing Box with Cone. This monotonous task seemed more suited for a computer than a human.

This led me to consider creating a generic class that would simplify this process:

var cube = new Shape('Cube', 20, 20, 20);
// or
var cone = new Shape('Cone', 20, 30);

I envisioned a scenario where this class could automate most of the work for me. Although I could extract the arguments from the function, I pondered on how to convert them from strings to logical statements efficiently.

Answer №1

Utilizing bracket notation enables you to create a function that accesses Three.<word>Geometry. By using rest syntax to gather the other arguments, you can then spread them into the constructor:

function generateShape(shapeType, ...arguments) {
  var material = new THREE.MeshNormalMaterial();
  var geometryShape = new THREE[shapeType + 'Geometry'](...arguments);
  var shape = new THREE.Mesh(geometryShape, material);
  shape.position.set(-10, -10, 0);
  scene.add(shape);
}

Simply invoke the function like this:

generateShape('Cube', 20, 20, 20);
generateShape('Cone', 20, 30);

If you wish to return something that was created in the function to the caller of generateShape, just use return at the end.

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

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...

"Enhance Your Website with Stylish Bootstrap Pop

Hello, I am trying to display a "Loading..." text or spinner image while waiting for the dynamic ajax content to load. Due to the large amount of data that needs to be fetched, it takes approximately 2-3 seconds for the content to fully load. Below is my ...

Saving maps on React Native can be done easily using AsyncStorage

I am facing an issue with saving user inputs as a JS map using AsyncStorage in my React Native app. Despite no errors during the saving process, I encountered "[object Map]" when attempting to retrieve the data. Here is a simplified version of my user map ...

Is there a way to transfer a JSON object to Excel using Nextjs/React?

How can I create a button that exports data from a JSON object to multiple file formats, including Excel (.xlsx)? "data": [ { "id": 1, "temaIndicador": "Indian", "codigo": "001", "observacion ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

What is the best way to apply "display: none;" on a span element nested within a title attribute?

I am utilizing the social-share-button gem to share blog posts on social media. The website has been internationalized, making it bilingual (English and German). Everything is functioning correctly, but I encounter an issue with the social share buttons wh ...

Setting up paths to bypass authentication on an Express website

Currently, I am in the process of developing an application using node and express. I have implemented a passport authorization middleware for all routes as part of my highly modular approach to building the app. One challenge I have encountered is when tr ...

Does a DOM API exist specifically for querying comment nodes within the document?

My document contains a debugging comment that appears as follows: <!--SERVER_TRACE {...}--> Is there a method to search the DOM and access this specific node? I would prefer a vanilla JavaScript solution, without relying on any external libraries. ...

Discovering ways to showcase JSON response in JavaScript or PHP

Currently, I am integrating the Coin Warz API into my website. The API sends responses in JSON format. I have attempted to display this data in a table format using PHP, but unfortunately, I am encountering difficulties. The JSON Response is as follows: [ ...

Having trouble deciphering this snippet of Express JS source code

Upon reviewing the Express JS source code, I came across the main module where express is being exported. module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; m ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

Having trouble with jQuery focus not functioning properly?

I've been attempting to implement a focus function on a specific input in order to display a div with the class name .search_by_name when focused. However, I'm encountering issues and would appreciate it if someone could review my code to identif ...

Exploring the power of V-for with checkboxes in VueJS

One issue I am facing is related to triggering my save method only when a checkbox is selected or true in Vue JS. I have no problem listing values and saving them to the database using axios, Vue JS, and Spring Boot. However, every time I click the checkbo ...

Measure the loading times of external web pages using JavaScript

I am seeking a minimalist approach to create a webpage on my server that utilizes JavaScript to calculate the loading time of the login page on various remote URLs/servers. These servers are dispersed globally, and my aim is to determine the quickest one f ...

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

I'm having trouble locating the module "script!foundation-sites/dist/foundation.min.js on Heroic."

This is the content of my webpack.config.js file: var webpack = require('webpack'); var path = require('path'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = { entry: [ 'script!jque ...

The selected option is not visually highlighted in the ui-select due to a programming issue

angular version: AngularJS v1.3.6 http://github.com/angular-ui/ui-select : Version: 0.8.3 var p1 = { name: 'Ramesh', email: '[email protected]', age: 99 }; $scope.people = [ { name: 'Amalie', ...

Issue with Angular 17 button click functionality not functioning as expected

Having trouble with a button that should trigger the function fun(). Here's the code snippet I'm using. In my TS file: fun(): void { this.test = 'You are my hero!'; alert('hello') } Here is the respective HTML: &l ...

Appropriate occasion for a concealed field in the user interface grid

Currently, I am utilizing the ui grid feature. Within this feature, there is an option called hide column. I am interested in receiving an event when a user hides a column. Specifically, I would like to display an alert when a column is hidden. Is there a ...

The module specifier "tslib" could not be resolved due to a TypeError. It is necessary for relative references to begin with either "/", "./", or "../"

Hey there, I recently started learning npm. I'm trying to install "@fullcalendar" and use it, but I keep getting this error message: "Uncaught TypeError: Failed to resolve module specifier "tslib". Relative references must start with either "/", "./", ...