A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations.

For example, when removing properties from objects, I usually use the following function:

function cloneOmit( obj, props ) {
  const keys = !Array.isArray(props)
    ? Object.keys(obj).filter(k => k !== props)
    : Object.keys(obj).filter(k => !props.includes(k));

  return keys.reduce(
    (clone, key) => {
      return { ...clone, [key]: obj[key] };
    },
    {}
  );
}

I adapted this function to work with Maps as well:

function cloneOmitMap( map, keys ) {
  const oldKeys = Array.from(map.keys());
  const newKeys = !Array.isArray(keys)
    ? oldKeys.filter(k => k !== keys)
    : oldKeys.filter(k => !keys.includes(k));

  return newKeys.reduce((newMap, key) => {
    return newMap.set(key, map.get(key));
  }, new Map());
}

This solution works, but I'm unsure about its performance and effectiveness. While I appreciate Maps for their iteration capabilities (using Object.keys() repetitively can be cumbersome), maintaining order insertion, and allowing any value as a key, they don't seem as conducive to pure operations as plain Objects are.

For example, adding a property to an object purely can be done simply like this:

const object = { foo: 'bar' }
const newObject= { ...object, fooFoo: 'barBar' }

I'm curious if there are any lesser-known Map operations that could facilitate working with them in a more pure manner, or perhaps a utility library that might help. Any guidance would be greatly appreciated!

Answer №1

I would suggest utilizing the iterator interfaces of Maps. Although creating multiple temporary immutable Maps may not be as efficient as using them mutably, iterators are generally faster than handling everything through array conversions.

If you incorporate these helpful functions into your code, it could appear like this:

function cloneOmit(map, keys) {
  const predicate = Array.isArray(keys)
    ? Set.prototype.has.bind(new Set(keys))
    : k => k === keys

  return new Map(filter(map.entries(), ([key, value]) => !predicate(key)));
}

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

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...

In what scenario should I respond with true or false to AJAX, and when is it more appropriate to use the echo function to output "true" or "false

It seems I have managed to confuse myself. I mistakenly believed that when using AJAX to communicate with PHP (like $.post), one had to echo back a "true" or "false" instead of simply returning true or false. I now realize this is not the case, but could ...

Moving Configuration Files in NextJS

When working on a typical Next.js project, I often end up with several root-level configuration files: tsconfig.json next.config.js next-seo-config.ts .eslintrc etc... I am looking to tidy up my root directory by moving these files into their own separat ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...

An issue with the JSON format encountered in the D3 pack layout

I am completely new to d3 and have only been learning it for the past 3 days. I attempted to create a pack layout, but I encountered an issue where I couldn't call the translate (or transform) function based on the data in an external json file. The s ...

Is there a way to ensure a function is only executed once whenever the page is refreshed?

I have the following code snippet: function myfunc () { alert('executed'); } $('.classname').on('click' function () { myfunc(); }); I am trying to ensure that myfunc is only executed once. I don't want it to ru ...

Rely on the razor method for generating URLs

I need to direct to a specific page, so I have implemented a JavaScript function in my MVC project: function rootUrl(url) { var _rootUrl = '@Url.Content("~")'; var x = url; if (url. ...

There seems to be an issue with the React Hooks edit form where it is not selecting the record to edit. Although the currentId is correct

I have a simple CRUD React Hooks app with an ASP.NET Core Web API. The Courses component displays a list, but when I click on a link to edit a particular course, the form shows up with empty fields. Here is the JSX for the Courses component: import React, ...

Type the query into the search bar on the website, hit the submit button, and receive the search results

Is there a way to dynamically pass any query string (from any oracle table, not hardcoded) from a webpage form/field to the database and have the webpage display a table/grid of the results without predefining columns or table names? Current examples I&apo ...

Could someone clarify the specific workings of the Google V8 bytecode related to the creation of object literals

Check out this awesome piece of JavaScript code! const person = { name: 'John', age: 30 }; console.log(person); Here's the Google V8 byte code generated by using node js option --print-bytecode. [generated bytecode for function:] ...

Seeking a sleeker approach to composing various components with shared functions

Currently, I have a scenario where I have identical components that display data but also need to handle state manipulation and saving. There are 5 other similar components with slight differences in their functions. I am looking for a more efficient way t ...

The React DOM element undergoes mounting and unmounting on each render cycle when it should be simply altered/updated

As per the React documentation, callback refs are invoked during both component mounting (with the DOM element's value) and unmounting (with null): When a React component mounts, the ref callback is triggered with the actual DOM element, and when it ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Exploring the power of hierarchical organization in node.js modules

One of my modules is called UserProvider and it has the following structure: var UserProvider = function(db) { ... } UserProvider.prototype.createUser = function(email, password, callback) { ... } UserProvider.prototype.findUserByEmail = function(email, c ...

Using axios with async/await to handle unresolved promises in Javascript

I'm facing a challenge with a piece of code I've been working on. Despite my efforts to find a solution online, I haven't had any success so far. Here is the code snippet in question: const fetchSidebarData = async () => { let da ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...