``There seems to be an issue with the toLocaleString function not properly formatting the

I have been tasked with writing a function that follows specific instructions, but for some reason, it is not working as expected.

Here are the guidelines:

Utilize the .toLocaleString function on both the amount and buyerCountry to format the amount into a currency with the currency symbol of the buyerCountry. The list of countries and their corresponding currency symbols can be found in the countries array provided in the starter code. If the buyerCountry is not listed in the countries array, default to United States and format the currency accordingly.

The code I have written does not seem to be compliant, and I am unsure why this is happening:

const countries = [
  {
      code: "US",
      currency: "USD",
      country: 'United States'
    },
    {
      code: "NG”,
      currency: "NGN”,
      country: “Nigeria”
    }
]

const formatAsMoney = (amount, buyerCountry) => {
  let toCurrency = '';
  countries.forEach(country => {
    try {
      if (value.country === buyerCountry) {
        toCurrency = (amount).toLocalString(value.code, {
          style: 'currency',
          currency: value.currency
        })
      }
    } catch (error) {
      toCurrency = (amount).toLocalString(en-US, {
        style: "currency",
        currency: "USD"
      });
    }
  });
  return toCurrency;
}

Could you please help me identify the issue and suggest how to fix it? Thank you!

Answer №1

When iterating through the countries array using:

countries.forEach(country => {...})

Make sure to use country to access values like country.code, country.currency, etc. It seems you are mistakenly using value.currency, value.code instead.

If we take a look at your countries array:

const countries = [{
        code: "en-US",
        currency: "USD",
        country: "United States"
    },
    {
        code: "en-NG",
        currency: "NGN",
        country: "Nigeria"
      }
]
const formatAsMoney = (amount, buyerCountry) => {
    let toCurrency = '';
    let isFound = false;
    countries.forEach(country => {
        if(country.code === buyerCountry) {
          toCurrency = (amount).toLocaleString(country.code, {style: 'currency', currency: country.currency});
          isFound = true;
        }     
      });
     if(!isFound){
        toCurrency = (amount).toLocaleString('en-US', {style: "currency", currency: "USD"});
     }
    return toCurrency;
  }

Note: There is a typo in toLocalString, it should be toLocaleString.

Check out the demo here

Answer №2

There are a few syntax errors in your code, as well as a logic problem that needs to be addressed.

Errors with Syntax

  • Ensure that string literals in JavaScript are quoted with either single quotes ', double quotes ", or backticks/grave accents. Avoid using the character .
  • The value 'en-US' should be enclosed in quotes when used as a parameter in toLocalString(). For example, use 'en-US'.
  • You have referenced a variable value without defining it. It seems like you intended to use country instead.
  • Be aware that there is no method called Number.prototype.toLocalString(); you most likely meant toLocaleString().

Logical Issue

The current implementation iterates through the countries array searching for matches. However, if no match is found, an empty string is returned instead of formatting the amount as currency in the 'en-US' format. The default formatting only takes place in case of an error.

To improve this, consider utilizing the find operation rather than iterating without an early-exit condition.


const countries = [{
  code: "US",
  currency: "USD",
  country: 'United States'
}, {
  code: "NG",
  currency: "NGN",
  country: "Nigeria"
}]

const formatAsMoney = (amount, buyerCountry) => {
  let country = countries.find(({ country }) => country === buyerCountry) || {
    code: 'US',
    currency: 'USD'
  }
  return amount.toLocaleString(country.code, {
    style: 'currency',
    currency: country.currency
  })
}

console.info(formatAsMoney(2.15, 'Nigeria'))
console.info(formatAsMoney(2.15, 'UK')) // not found

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

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

Is it possible to save an array as a string in a MySQL database?

Is this considered a good practice? I am planning to save bookmarks, with each bookmark being stored as a row in the table. I intend to have a tag column that will essentially be an array in string format holding the hierarchy of tags defining it. For ins ...

React - Dynamic form causes input to lose focus after typing just one character

My goal is to design a dynamic form where users can add multiple books, each with a name and link. Currently, I have an "Add a Book" button that successfully adds fields to my form. However, when I try to type in any of these fields, the input loses focus ...

Is there a way to refresh CSS styles when the window width is adjusted?

Is there a way to refresh CSS styles when the window width changes? I attempted this method, but unfortunately it did not work as expected. A simple refresh (F5) helps to rectify the CSS tags. jQuery(function($){ var windowWidth = $(window).width(); ...

Ways to extract data from a chosen radio button choice

Excuse me, I have a form with an input field and radio buttons. Can someone please help me with how to retrieve the value of the selected radio button and then populate that value into the input text field? For reference, here is the link to the jsfiddle: ...

Embed a YouTube video within the product image gallery

Having trouble incorporating a YouTube video into my Product Image Gallery. Currently, the main product photo is a large image with thumbnails that change it. You can see an example on my website here. Whenever I attempt to add a video using the code below ...

The React button fails to refresh the display

I am working on creating a dynamic input form that, when clicking a button, will generate a new row of description input fields. To keep track of these descriptions, I am using an array within the state: state = { descriptions: [ { ...

Upon initializing mean.io assetmanager, a javascript error is encountered

I am eager to utilize the MEAN.io stack. I completed all the necessary initialization steps such as creating the folder, performing npm install, and obtaining the required libraries. Currently, in server/config/express.js file, I have the following code: ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

What are the most widely used NodeJS framework and library choices currently available?

I am embarking on the exciting journey of building a robust application using NodeJS. As someone new to Node, I believe it would be beneficial to gather insights from experienced developers in the field. While researching, I have come across positive feed ...

Angular Flot Chart Resizing: A Guide to Dynamic Chart S

I have successfully integrated a Flot chart into my HTML using an Angular directive. Here is how it looks: <flot id="placeholder" dataset="dataset" options="options" height="300px" width="100%" style="width:100%;" ng-disabled="graphLoading" ng-class="{ ...

IE9 not executing AngularJS filter

Currently, I am encountering an issue with my custom filter in AngularJS 1.2.22 on IE9. Interestingly, the filter works perfectly fine on Chrome and Firefox, but unfortunately not on the browser that is essential for me. The problem lies within two filter ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...

AngularJs - Show the response only upon verifying the correct answer

Let me provide an overview of what has been implemented so far: When a user selects an answer in radio buttons and clicks on "Check Answer", the system displays either "Correct" (in green) or "Incorrect" (in red) in the first answer field. Additionally, th ...

Would the Client fail to recognize the Server's response if it is in text/html format?

I attempted to remove a JWT token using the localStorage.removeItem() function, but encountered an issue when running the following code. I am developing with JavaScript and Express.js in Visual Studio Code, and using the Chrome browser. [Client] secess ...

Enforcement of Typescript Field Type Lax During Assignment

My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is ...

Is it possible to conduct a feature test to verify the limitations of HTML5 audio on

Is there a way to detect if volume control of HTML5 audio elements is possible on iOS devices? I want to remove UI elements related to the volume if it's not alterable. After referring to: http://developer.apple.com/library/safari/#documentation/Aud ...

A step-by-step guide on extracting all documents within a directory collection from the official national archives website using the R programming language

I'm currently seeking a way to scrape all available files for a data file series on archive.gov programmatically using R. It seems that archives.gov utilizes JavaScript. My objective is to extract the URL of each available file along with its name. T ...

Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of l ...