``Converting objects to key-value pairs in JavaScript like Scala's `toMap

Is there a more idiomatic JavaScript solution for this situation:

const addTuple = (map, tuple) => { map[tuple[0]] = tuple[1]; return map; };

I am looking to refactor this example (refer to finance3.js) in a more functional style:

angular.module('finance3', [])
.factory('currencyConverter', ['$http', function($http) {
      let rates = {}; // Ideally should be a future (or some other monad) mapped from $http.success, but it's challenging to do with JavaScript
      const processRate = (rate) => {
          return [rate.id.substring(3, 6), window.parseFloat(rate.Rate)];
      };
      const addTuple = (map, tuple) => { map[tuple[0]] = tuple[1]; return map; };
      $http.jsonp(url).success(function(data) {     
          rates = data.query.results.rate.map(processRate).reduce(addTuple, {});
      });  
     return rates;
}]);

Therefore, .reduce(addTuple, {}) can be seen as equivalent to toMap in this context.

P.S. On a side note, KnockoutJs offers a more reactive (albeit still non-pure functional) approach to updating the model.

Answer №1

If you have access to an external library, consider using lodash. It offers functions like _.pairs and _.zipObject that can help transform objects into arrays of two-dimensional arrays (e.g., from {key: value} to [[key: value]]) and vice versa.

var x = _.pairs({ 'barney': 36, 'fred': 40 });
// [['barney', 36], ['fred', 40]]

var y = _.zipObject(x)
// { 'fred': 40, 'barney': 36 }

A simple way to refactor your code is

rates = _.zipObject(data.query.results.rate.map(processRate))

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

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...

Utilize Angular2 with ES6 modules while running an Express server

Having some issues using ES6 Modules with Angular2 in an app served by Node.js and Express.js. When attempting to load the Angular2/ES6 app in browser, encountered this error message in the FireFox console: The stylesheet http://localhost:8080/boot.css w ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...

Unable to confirm form validation with Vue

Recently, I started working with Vue and encountered a problem while running the code below. The error message "ReferenceError: $vAddress is not defined" keeps popping up. Despite my efforts to search for solutions online, I couldn't find any that add ...

Obtain the default/initial argument type of typescript for extension purposes

Currently, I am in the process of developing code that automatically generates type hints based on function calls related to GraphQL Nexus tasks. In one of its functions, it requires an anonymous type constructed from the attributes generated automaticall ...

Step-by-step guide on visually comparing two iframes for differences

Scenario : In my project, I am dealing with 2 iframes that contain a significant number of divs and other controls, making both iframes similar in size to complete HTML websites. My goal is to compare these two iframes and identify any differences. Consi ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

I am interested in redirecting command line output to a file rather than displaying it in the standard

Is it possible to use child-process and spawn in node.js to execute a command and save the output to a file instead of displaying it on the standard output? test.js const expect = require('chai').expect; const { spawn } = require('child_pr ...

Polymer Google Maps Marker OnClick Function

I am struggling to trigger a click event for a google maps marker while utilizing the Polymer web component. After reviewing this question on Stack Overflow, I have noticed a minor difference in my code that may be causing issues. My implementation invol ...

Issues with jQuery .click and .html functions not functioning as expected

Does anyone have experience creating a game with jQuery? I can't seem to get the options after the first choice to work. Sorry, I don't have a working example at the moment. --- jQuery --- $(document).ready(function() { $(".console"). ...

React Select feature fails to show suggestions after asynchronous debounced call

I am currently utilizing react-select to load results from an API while debouncing queries using lodash.debounce: import React, {useState} from 'react'; import AsyncSelect from 'react-select/lib/Async'; import debounce from 'lodas ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

Troubleshooting JavaScript within Embedded Resources

Looking for the most effective method of debugging JavaScript in Visual Studio when dealing with embedded resource files? Due to the fact that JavaScript is compiled into a library, setting breakpoints directly on the source file may not yield desired res ...

Tips for eliminating flicker upon the initial loading of a webpage caused by dynamic changes in CSS styles through JavaScript

Struggling with the load order of my CSS and JavaScript... Currently, I have a div with a blue background that is styled to appear sliced diagonally. However, upon initial page load (or CTRL+SHIFT+R), there's a brief moment where the slice effect doe ...

Populate an HTML table with the days of the month and corresponding dates retrieved from a PostgreSQL database using JavaScript

I'm struggling to figure out how to use generate_series to populate an HTML table where the 'key' of <tr> corresponds to the days of the selected month and year using an <input type='month'>. So far, with the help I re ...

Discover the method to retrieve the chosen value from a list of radio buttons using AngularJS

After making an AJAX request and receiving JSON data, I have created a list of radio buttons with values from the response. Although I have successfully bound the values to the list, I am facing difficulty in retrieving the selected value. Below is a snipp ...

Can you explain the purpose of using the 'apply' method in this particular implementation of memoization in JavaScript?

_.memoize = function(func) { var cache = []; return function(n){ if(cache[n]){ return cache[n]; } cache[n] = func.apply(this,arguments); return cache[n]; } }; I'm curious about the usage of 'this' in func.appl ...

Customize hover effects in tailwind css with dynamic values

I am trying to customize the text color on hover based on different category names using tailwind CSS. In my configuration, I have assigned a specific color code for each category like this : tailwind.config.js theme: { extend: { } }, co ...

Encountering difficulty retrieving information in an Angular application on an iPad mini device

I am currently developing an angular application for a dashboard. The issue I am facing is related to making http requests from my controllers. Everything works perfectly when I build and run the project using grunt on my machine, fetching data from the ex ...