What would be the most stylish approach to restructure this code, especially when the only variation is the name of the key in the returned object?

Is there a more elegant solution for restructuring this code, especially considering the only variation is in the key name of a return object?

function generateContactInput(rawData, contactId) {
  const data = rawData
    ? rawData.replace(/["]+/g, '').split(SEMICOLON)
    : undefined;
  const populatedData = data
    ? data.map((value) => ({ contactId, value }))
    : undefined;
  if (Array.isArray(populatedData) && populatedData.length > 0)
    populatedData[0].isPrimary = true;
  return populatedData;
}

function generateContactAddressInput(rawAddresses, contactId) {
  const data = rawAddresses
    ? rawAddresses.replace(/["]+/g, '').split(SEMICOLON)
    : undefined;
  const populatedData = data
    ? data.map((streetAddress) => ({ contactId, streetAddress }))
    : undefined;
  if (Array.isArray(populatedData) && populatedData.length > 0)
    populatedData[0].isPrimary = true;
  return populatedData;
}

The distinguishing line is:

? data.map((streetAddress) => ({ contactId, streetAddress }))

Answer №1

If you're keen on exploring the functional programming paradigm, feel free to reach out

const combine = (...functions: any[]) => (data: any) => functions.reduceRight((accumulator, fn) => fn(accumulator), data);

const SEMICOLON = ';'

const extractInfo = (id, title) => (value) => ({ id, [title]: value })

const modify = (rawData) => rawData ? rawData.replace(/["]+/g, '').split(SEMICOLON) : undefined

const process = (callback) => (data) => data ? data.map(callback) : undefined

const convertToArray = (data) => {
    if (Array.isArray(data) && data.length > 0) {
        const [firstElement, ...rest] = data

        const updatedFirstElement = {
            ...firstElement,
            isPrimary: true
        }
        return [updatedFirstElement, ...rest]
    }

    return data
}

const execute = (rawData, id, method: 'value' | 'streetAddress') =>
    combine(convertToArray, process(extractInfo(id, method)), modify)(rawData)

Check out this resource for a detailed explanation of my combine function

Answer №2

One effective strategy involves developing a single helper function that takes a specific name for mapping:

function generateInput(rawData, contactId, fieldName) {
  const data = rawData
    ? rawData.replace(/["]+/g, '').split(SEMICOLON)
    : undefined;
  const populatedData = data
    ? data.map((value) => ({ contactId, [fieldName]: value }))
    : undefined;
  if (Array.isArray(populatedData) && populatedData.length > 0)
    populatedData[0].isPrimary = true;
  return populatedData;
}

... you can then either directly utilize this helper function or form a range of wrappers with preset values:

function generateContactInput(rawData, contactId) {
  return generateInput(rawData, contactId, 'value');
}

function generateContactAddressInput(rawData, contactId) {
  return generateInput(rawData, contactId, 'streetAddress');
}

In fact, I would recommend reconsidering the code to eliminate the ternaries as well:

function generateInput(rawData, contactId, fieldName) {
  if (!rawData) return; // it's unnecessary to propagate this special case 
      
  const data = rawData.replace(/["]+/g, '').split(SEMICOLON);
  const populatedData = data.map((value) => ({ contactId, [fieldName]: value }));
  if (populatedData.length > 0) 
    populatedData[0].isPrimary = true;
  return populatedData;
}

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

Unreachable variable in Vue 2.0

I am new to Vue and facing an issue with accessibility. I have two files. The first file is App.vue where <router-view> is defined: <script> export default { name: 'app', data(){ return{ info: false, } }, befo ...

What is the process for invoking an asynchronous cleanup function?

Is it possible to trigger an async cleanup function within useEffect? useEffect(() => { return () => Voice.destroy().then(Voice.removeAllListeners); }, []); Keep in mind that the EffectCallback requires a return of void, not Promise<void> ...

Transmit information using express handlebars in a straightforward node application

Struggling to pass data from express handlebars to index.html? Check out my code below: server.js code: const express = require('express'); const app = express(); const expressHandlebars = require('express-handlebars'); const path = r ...

React canvas losing its WebGL context

What is the best practice for implementing a webglcontextlost event handler for React canvas components? class CanvasComponent extends React.Component { componentDidMount() { const canvasDOMNode = this.refs.canvas.getDOMNode(); DrawMod ...

I'm confused about this CallbackRouteError with the provider named "credentials". Can someone please explain?

I can't seem to resolve this error after searching extensively on the web. For more information, visit [auth][error] CallbackRouteError: For more details, please visit https://errors.authjs.dev#callbackrouteerror [auth][cause]: Error at Module.callb ...

Ways to eliminate nested properties in JSON.stringify()

Looking to make alterations to a string using Typescript. The string is generated by the JSON.stringify() function. I aim to eliminate the attributes "id", "lightStatus", and "value" from both "inputPort" and "outputPort" objects, only keeping their respe ...

Retrieving a Promise's value for an HTML Element

Hello, I'm new to working with React and JavaScript and could use some assistance. I have a function that returns a Promise that includes an interface. My goal is to access a variable in the interface and use it within <dl><dt>{//string va ...

What could be the reason for TypeScript throwing an error despite having a condition in place?

Having an issue with TypeScript (TS2531) and its non-null type checking. Here's the scenario: if (this.formGroup.get('inseeActivityCode') !== null) { mergedCompanyActivity.inseeActivityCode = this.formGroup.get('inseeActivityCode&ap ...

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

Tips for safely storing data in local storage using Angular 5

How can I securely store data in local storage, such as encrypting and decrypting the local storage data to prevent manipulation by other users? If it's not possible with local storage, what are alternative methods for client-side data storage? I&apo ...

Inquiries regarding code optimization with Selenium

Using Selenium IDE, I created a script to test logging into a website and verifying a value on the site after logging in. Here is my Java script: @test public void mytest() throws Exception{ // Load the home page ... // Complete the log form ... ...

Encountering difficulties in generating a personalized Angular Element

Currently, I am in the process of developing a custom Component that needs to be registered to a module. Here is how it is being done: app.module.ts import { createCustomElement } from "@angular/elements"; @NgModule({ declarations: [ExtensionCompone ...

What steps should I take to resolve an unhandled promise error in a React TypeScript application while making an axios POST request?

I am currently working on a .tsx file to implement adding an enterprise feature. Although I can input data, clicking the submit button does not trigger any action. My application includes a page that has a button for adding a new enterprise. Upon clickin ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

Automated Async Saving in Angular 2 using Typescript

I am currently working on implementing an autosave feature in TypeScript. The main objective is to automatically save any text input by the user every 10 seconds to prevent loss of data in case of a page crash or accidental closure. I aim to initiate the a ...

Utilizing Typescript to Load JSON File into React Context Provider

I have a React Typescript app with a Context Provider called DataProvider. The purpose of this provider is to read a value from a JSON file and make it available in the Context through useData(). I want to perform the file read operation synchronously to a ...

Calculating the minimum value of a number in Angular 8

I attempted to convert a decimal number to a whole number and encountered an issue. When using the angular pipe method {{myNumber | number: '1.0-0.'}}, it provides a rounded off value instead of the floor value. For example, with number = 3.8, ...

Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do ...

The canActivate: [AuthGuard] feature on the external router is not functioning as expected

I'm encountering an issue with my routing. I attempted to use the following code: const routes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [AuthGuard], children: [ { path: 'events', component: Ev ...