There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it. Thanks in advance. I have closely followed all the guidelines of JavaScript programming, yet there seems to be a glitch somewhere that I can't pinpoint. Also, I have successfully implemented a working version of the script in PHP, which you can find in the second script of this post: PHP split string at last number, insert an extra string and merge the new string.


function calTime(x) {
  // Function code here...
}
document.getElementById("demo").innerHTML = calTime(83200);

Answer №1

I will compile all the technical mistakes in the script into one concise list.

  1. Time calculations are incorrect

    The script contains inaccurate time calculations. For instance, it assumes there are 86400 seconds in a day and 31536000 seconds in a year. It is recommended to utilize predefined values instead of hardcoding them.

  2. Using indexOf() on incompatible objects

    There is a common mistake in the script where the indexOf() method is applied to numbers without converting them to strings first. To avoid errors, ensure that any non-string objects are converted appropriately before using string methods on them.

  3. Failure to check the return value of indexOf()

    It's crucial to properly assess the return value of indexOf(). The script overlooks the possibility of returning -1 when the string is not found, leading to erroneous logic in handling scientific notation formats.

  4. Ignoring case sensitivity in scientific notation

    Due to different representations of small values, the script may fail to match certain patterns. Consider using Math.floor() universally to address floating-point precision issues more effectively.

  5. Disregarding the return value from Math.floor()

    In multiple instances, Math.floor() is used without updating the original variable with the floored result. Make sure to assign the new value back to the variable for accurate computations.

  6. Converting time components improperly

    The script stores time components as strings but filters them using Number, causing unexpected results. Modify the filtering process by implementing a function within the filter() method to handle empty string entries correctly.

  7. Incorrect usage of count() on arrays

    A statement involving count() appears, which does not belong to JavaScript Array methods. Replace this with length to obtain the number of elements in an array accurately.

  8. Duplicating the last item in the time array

    There is a redundancy issue where the last element of the time array is duplicated during concatenation. This should be resolved to prevent unnecessary repetition and account for evenly dividing time categories.

These technical flaws need attention in the script. Alternative approaches could also be explored to enhance the script's efficiency and readability.

Answer №2

Adding to the already provided answers, a major style issue in your code is the excessive repetition that can be eliminated by utilizing loops and functions.

Furthermore, the mathematical calculations could be simplified significantly, rendering the need to search for 'E' or '.' unnecessary. Considering this, using a loop may not be necessary; in the example below, a loop is only employed to add labels. It's advisable to use descriptive variable names (hours, minutes instead of a, b) whenever possible to enhance code readability.

Visit this link for reference.

function calculateTime(seconds) {
    if (seconds === '') {
        seconds = 54098;
    } // Time value converted to seconds
    seconds = Math.floor(seconds);
    if (isNaN(seconds) || seconds <= 0) {
        return '<i>No time specified</i>';
    }
    var minutes = Math.floor(seconds / 60), 
        hours = Math.floor(minutes / 60),
        days = Math.floor(hours / 24), 
        years = Math.floor(days / 365), // assuming non-leap year!
        timeData = [years, days % 365, hours % 24, minutes % 60, seconds % 60],
        pluralLabels = ['years', 'days', 'hours', 'minutes' , 'seconds'],
        singularLabels = ['year', 'day', 'hour', 'minute', 'second'],
        time = [];
    for (var i = 0; i < timeData.length; i++) {
        if (timeData[i] > 1) {
            time.push(timeData[i] + ' ' + pluralLabels[i]);
        }
        else if (timeData[i] > 0) {
            time.push(timeData[i] + ' ' + singularLabels[i]);
        }
    }
    var lastEntry = time.pop();
    return time.length ? time.join(', ') + ' and ' + lastEntry : lastEntry;
}
document.getElementById("result").innerHTML = calculateTime(83200);

Check out this alternative method which utilizes loops more efficiently for mathematical computations.

Answer №3

Your variables a, b, and other letters represent numbers in this context. The indexOf method is specifically designed for use with strings in JavaScript.

To address this issue, one solution would involve converting your numbers into strings, such as:

a = a + "";

This adjustment will help eliminate the errors related to the use of indexOf()

Furthermore, it seems that there may be misuse of functions present within your code. An example of this is the mention of a count() method which does not seem to be a valid function in JavaScript.

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

Tips on incorporating a URL from a text file into a string

Could anyone assist me in adding a URL text file containing just one sentence and saving it as a string? Your help would be greatly appreciated. Thank you. ...

Tips for transferring information from Django to React without relying on a database

Currently, I am in the process of developing a dashboard application using Django and React. The data for the user is being pulled from the Dynamics CRM API. To accomplish this, I have implemented a Python function that retrieves all necessary informatio ...

Issue with Textarea not updating when props change in a React component

I am facing an issue with updating the default value of a textarea based on props passed from a parent component. Strangely, the update works when using 'value' but not when using 'defaultValue'. However, I need the textarea to be edita ...

Getting the full referrer URL can be achieved by using various methods depending

I am currently working with ASP.Net. My goal is to retrieve the complete referrer URL when visitors arrive at my website from: https://www.google.co.il/webhp?sourceid=chrome-instant&rlz=1C1CHEU_iwIL457IL457&ion=1&espv=2&ie=UTF-8#q=%D7%90 ...

Arrays data being retrieved and set by Chrome Extension are visible in the console but not appearing in the HTML

Having trouble displaying my arrays in HTML. I'm attempting to do this within a Chrome Extension. While I can view the array perfectly in console.log, I'm encountering issues when trying to add it to the HTML DOM: /* Generating the array f ...

Is there a way to insert json data into a form input field using jQuery?

I am attempting to insert the JSON result into an input as the value. This is the code I am using: $.ajax({ type:"POST", url: '{% url "url_searchTour"%}', data: data1, success: function(jsonAjaxResult){ console.log(J ...

I aim to trigger a Redux action utilizing react-router-dom

In light of a route adjustment, I am in search of an improved method for invoking the redux action. One option is to invoke a redux action through the render function, as shown below: render(){ const filterName = this.props.match.params.product this.p ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

The parameters passed in an axios get request are not carried over to a create request

Exploring the capabilities of the YouTube API with ReactJS While working with the YouTube API, I came across the create method in axios. However, I faced an issue where the params were getting overwritten. What am I missing here? I have a file named yout ...

Utilize React Material UI to dynamically update state with Slider interactions

Currently, I am in the process of developing a multi-step form (survey) using React.js and the Material-UI components library. However, I have encountered an issue with the slider component at one of the steps – it does not seem to update the state as ex ...

Looking for some guidance on grasping the concept of strict mode in React and determining what actions can be considered side effects

The other day, I came across a strange bug in React and here is a simplified version of it. let count = 0; export default function App() { const [countState, setCountState] = useState(count); const [countState2, setCountState2] = useState(count); con ...

Uploading a Node.js Package to GitHub Packages - Issue ENEEDAUTH

Hello everyone, I am currently attempting to deploy my NPM package to GitHub packages using the following yaml configuration: # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created # For m ...

Disabling the Enter key to submit an AJAX form is causing the focus to not move to the next input field

I've encountered a small issue that I can't seem to find a solution for (maybe my keyword search wasn't effective): The scenario: I have successfully prevented a form from being submitted when hitting the Enter key (13). It's importan ...

To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure. obj = {WHERE:{antherObject},OPTIONS{anotherObject}} Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key? I thoug ...

Unlocking the Power of $http and Stream Fusion

I'm interested in accessing the public stream of App.net. However, when I attempt to retrieve it using a simple $http.get(), I only receive one response. $http .get('https://alpha-api.app.net/stream/0/posts/stream/global') .success(func ...

Replicate the preceding input data by simply clicking a button

Here is some HTML and jQuery code that I am working with: $(".btn-copy").click(function() { var previousContent = $(this).prev()[0]; previousContent.select(); document.execCommand('copy'); }); <script src="https://cdnjs.cloudflare.com ...

A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implemen ...

What causes the indexOf method to return -1 even when the values are present in the array?

Could someone explain why the indexOf() method returns -1 even though the values are present in the array? The includes() function also returns false for me. I feel like I must be missing something or forgetting a crucial detail. Any insights on why the ...

Making AJAX requests to retrieve data from a JSON database array, then utilizing the CSS visibility property to conceal HTML elements dynamically

As a enthusiastic beginner, I'm facing a challenge that seems to have no easy solution. Can someone please assist me with this: How can I assign all the ids from a JSON database to the variable dotContainer, in order to hide all corresponding HTML id ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...