JavaScript - creating mathematical expressions without the need for operator overloading

In my JavaScript project, I am utilizing three.js and attempting to determine if a vector remains within a designated area as shown below:

var THRESHOLD = 10;
if (!is_in_rect(camera.position - forward * THRESHOLD))
    // do something

where camera.position and foward are THREE.Vector3 objects.

The issue with the method described above is that even though it is easily understood, it's ineffective due to Javascript lacking operator overloading. As a result, I have to resort to coding it like this:

if (!in_rect(camera.position.clone().add(forward.clone().multiplyScalar(THRESHOLD)))

and personally, I find it quite unappealing.

Is there a more natural way in JavaScript to achieve this functionality that I might be overlooking?

Answer №1

After reviewing the information provided on the linked page:

.addScaledVector ( v, s )

This function adds a scaled version of vector v to this vector.

A more optimized approach would be:

camera.position.clone().addScaledVector(forward, THRESHOLD)

It's unnecessary to clone forward since it will not be altered in this scenario.

If I understand @T.J.'s suggestion correctly and you're looking for a more widely applicable solution, my response would be that if by 'idomatic' you mean utilizing the + and - operators in JavaScript strictly, then no. You could potentially create your own framework to adhere to idiomatic standards, like implementing a general addition operator:

var add = function(x,y):
    try {
         var sum = x + y;
         if ( s != undefined ) { return sum; }
         #otherwise
         sum = x.clone().add(y);
    } catch {
        #Otherwise threw something
        sum = x.add(y) #maybe another exception? nest try/catch.
    }
}

However, this approach entails a considerable amount of effort due to the need for extensive type checking, as JavaScript allows for loose concatenation of values without strict rules. Simply attempting to return x+y may result in an undefined output. In my illustration, prioritizing add functions over basic arithmetic operations might yield better results.

This method enables you to establish the desired programming style, should you find it worthwhile, and use your customized add function across different tasks instead of relying on the standard + operator. It's advisable to expand upon this concept during your coding process.

Answer №2

Is there a different way to accomplish this task in JavaScript that I might not be aware of?

Not really, you would essentially need to create your own expression parser or utilize an existing one.

A couple of points to consider:

  1. It may be slightly easier with ES2015+'s template literals and tagged template functions, as it handles some parsing for you. You could potentially create a tag function like:

    if(!is_in_rect(threval`${camera.position} - ${forward} * ${THRESHOLD}`)))
    

    The `threval` function would receive the raw strings array from the template literal, followed by values for camera.position, forward, and THRESHOLD. This information can then be used to construct the sequence. However, this approach would be complex.

  2. You have the option to develop a Babel plugin to elevate your expressions to first-class constructs and transpile them. The benefit is that Babel offers a robust parsing infrastructure and support tools.

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

Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated! Example needed:- https://i.sstatic.net/DF8Wn.png $(docum ...

Ways to integrate a security protocol with a graphql resolver

I'm currently diving into the world of graphql and I'm facing a challenge with incorporating an authentication/authorization system into my project. I stumbled upon an example on Medium, but I'm struggling to grasp how a guard connects with ...

Tone.js puts an end to all currently playing sounds

With just a button press, I want to play a sequence of notes using a PolySynth and a Sequence. When the button is pressed repeatedly, I want the currently playing notes to stop and restart. The challenge: No matter what method I use, I can't seem to ...

Implementing pagination in a node.js application using pg-promise and fetching data from

Upon reviewing the documentation at https://github.com/vitaly-t/pg-promise/wiki/Data-Imports, I found a comprehensive guide on importing data using pg-promise. Although the example provided works for the showcased scenario, I am unsure how to adapt it to ...

The concept of recursion in AngularJS directives

I developed a unique custom directive. angular.module('menu',[]) .directive('MenuDirective',function(){ return{ restrict:'E', replace:'true', scope:{ m ...

Exploring ways to enhance the display of lines in webgl, specifically utilizing the capabilities of the three.js framework

Recently I delved into the world of webGL and made the decision to utilize the Three.js library. As part of my project, I am currently facing the challenge of rendering over 100,000 cubes while also attempting to connect these cubes with lines. The issue ...

Encountering a Typescript error while attempting to iterate through Enum keys for generating JSX components

I'm really struggling with this problem. Here's a simple enum I have: export enum depositTypes { ACH = 42, Wire = 36, Check = 3, Credit = 2, } I'm trying to create option tags for a select element, like so: Object.keys(depositTyp ...

What is the best way in jQuery to display a particular div with a unique id when a link is clicked?

I have a div with the following structure: <article id="#pippo">blablabla</article> which I have hidden using jQuery $('article').hide(); Now, I want to create a link menu that displays a specific article id when it's clicked ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...

Organizing multiple <image> tags into an array with Javascript - a beginner's guide!

My HTML file contains multiple images. When a user clicks on them, their IDs should be captured without any issues. I am looking for help with the following tasks: 1) Storing all clicked image IDs in an array For example: array = img01 ; array = img ...

Using Vue JS to set a default value in a custom radio group

Recently, I attempted to implement a default value in a custom radio component that I developed. Below is the code snippet: <template> <div class="custom-radio-button"> {{value}} <div v-for= "item in localValue"> <input type ...

When choosing from multiple dropdown menus, the selected option should be hidden from the other dropdowns

I'm currently working on a project that involves designing a web form incorporating 3 select boxes with multiple questions. The concept is such that, if I choose the 1st Question from the 1st select drop-down, it should not be available in the 2nd sel ...

Tips on retrieving a result from mongoose's findOne() function

I created a custom function using the findOne() method in Mongoose and now I need to use the result for another function. How can this be achieved? Thank you! module.exports.retrieveDeal = function(dealRequest){ Deal.findOne({name:dealRequest},functi ...

Are third-party scripts and HTML widgets able to replicate your website's data, including cookies, HTML, and other elements?

Currently, I am in the process of constructing a website that incorporates a third-party weather HTML widget. The widget is sourced from a trusted and reliable source on the web. It consists of a link and small JavaScript tags that are executed once loaded ...

Exploring the Depths of NodeJS X-Ray Web-Scraper: Uncovering Hidden Gems within Sub Pages

Currently, I am attempting to scrape content using the node.js x-ray scraping framework. While I have successfully retrieved data from a single page, I am struggling with navigating through links and extracting content from subpages simultaneously. Althou ...

Tips for simulating the 'this' keyword within Jest test scenarios

Within my JS script, there is a similar structure: window.custom_object = { //custom function defined myFunction: function(param1,param2){ } myNewFunction : function(){ //attempting to call myFunction ...

Transforming a two-digit year into a four-digit year

Our entry form provides users with a calendar drop-down option, but they are also able to manually type in dates. We recently discovered that if someone enters a 2-digit year, it automatically changes to 1912 instead of 2012 (as dates cannot be in the past ...

When using `defineModel` in Vue, the returned value can be either an object or

defineModel() is a new feature introduced in Vue 3.4+. The official documentation provides the following example: const model = defineModel() model.value = 'hello' Initially, it appears that model is an object with a value property. However, th ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

Attempting to extract data from an external JSON file in order to dynamically generate markers for the Google Maps API

Using JavaScript and an external JSON file, I have the JSON data stored in a file named csus_locations.JSON within the same folder as my js file. Here is a snippet of the JSON data: { "locations": [ { "latitude": 38.558961, "longitude": -121.42 ...