What is the best way to streamline a state-dependent getter, with a focus on adhering to SOLID principles?

Is there a more user-friendly way to retrieve different data based on the type in my Angular component?

I'm considering separating the component into two: one for phone and one for email. However, I'm concerned about duplicating most of the logic.

let getContactInfo;
let hasContactInfo;

if(type === 'email') {
    getContactInfo = (profile) => profile.getEmail();
    hasContactInfo = (profile) => profile.hasEmail();
} else if(type === 'phone') {
    getContactInfo = (profile) => profile.getPhone();
    hasContactInfo = (profile) => profile.hasPhone();
}

Answer №1

In my approach, I would have utilized an object that maps the methods based on the type:

const createContactInfo = (fetchContactInfo, checkContactInfo) => ({ fetchContactInfo, checkContactInfo });

const contactInfoTypes = {
  email: createContactInfo((profile) => profile.getEmail(), (profile) => profile.hasEmail()),
  phone: createContactInfo((profile) => profile.getPhone(), (profile) => profile.hasPhone())
};

Then, during invocation:

const selectedContactInfo = contactInfoTypes[type];
if (!selectedContactInfo) {
  throw new Error(`No contact information matched the type '${type}'`);
} else {
  selectedContactInfo.checkContactInfo(profile);
  selectedContactInfo.fetchContactInfo(profile);
}

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

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...

The functionality of the Datepicker popup box is slightly affected by Angular's $compile method

UPDATE 1: additional details have been included. UPDATE 2: the plunker code has been added to replicate the issue. Refer to the link provided below. UPDATE 3: I received a response from the Angular team on github. You can view it here. UPDATE 4: An u ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

Angular Express: PUT request causes nested array object to be stripped

I have been facing an issue while trying to update my MongoDB database with data sent from the client side using Angular. The PUT request contains the required data as confirmed by intercepting it with Postman. {val1: 'Some Val', val2:[{v21: &ap ...

Utilizing ng-switch for handling null values or empty strings

Can anyone assist me with this issue? I have a variable called $rootScope.user = {name:"abc",password:"asd"}. When a service response occurs, I am dynamically creating a rootscope variable by assigning it. How can I use ng-switch to check if the variable h ...

VueJS failing to pass parent data to child component

I'm fairly new to Vue Framework and I'm trying to figure out how to update a child component based on changes in the parent component's attributes. In the code snippet below, I've created a component that displays a greeting message bas ...

Transform all the characters within p tags using the JavaScript replace method

Currently, I am dealing with data displayed on my website that comes from an XML feed. However, the issue lies in the fact that the owner of the XML feed has used grave accents (`) instead of apostrophes ('). To address this problem, I have implement ...

How can I show tab objects in a Chrome extension?

I'm currently working on developing a new Google Chrome extension that focuses on tab organization. Despite the abundance of similar extensions already available, I am determined to create my own unique solution. One idea I have is to create a popup w ...

Utilize the directive method within the transcluded content by making a call

Trying to call a method within a directive from transcluded content. The structure of my HTML is: <typeahead class="typeahead" model="customers" filtered-model="customersfiltered" ng-model="selectedcustomer"> <ul> <li ng-click="select ...

Can Jquery mobile detect drag gestures?

Is there an event in Jquery Mobile that allows you to hide/show a div by dragging it, similar to the effect seen on phones? I have searched on different platforms and found that using Jquery UI is the closest solution. Is it possible to achieve this only ...

Is there a way to construct a Javascript function, without relying on JQuery, for fetching JSON objects from varying

I have been searching for a non-JQuery AJAX function that can fetch data from a URL and return it as a JSON object. For example, let's say I want to display information about Users from one JSON located at URL1 and also include information about Post ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

Expanding functions consist of numerous components

How can I modify this script to work on multiple elements? For example, if a user clicks on a specific link (see demo) labeled "I'd like to expand the article linked here", only that particular link should expand an element, not all like it currently ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

Implementing a pop-up notification at the center of the display for empty fields

I am currently working on a task that requires me to display a pop-up message at the top-middle of the screen stating "please fill in all fields before submitting". This custom box should be stylable using CSS. Although the solution seems simple, I am str ...

Combining the power of Angular.js and Require.js

As I develop a local app on nw.js using angular.js, I'm starting to question my approach. In my controller, I often find myself writing code like this: .controller('UserSettingsCtrl', function($scope, $mdDialog, $translate) { var fs = ...

The initialization of the Angular service is experiencing issues

I have a service in place that checks user authentication to determine whether to redirect them to the login page or the logged-in area. services.js: var servicesModule = angular.module('servicesModule', []); servicesModule.service('login ...

Guide to receiving dynamic argument variables in jQuery using $.get

I am currently working on developing an Ajax function call. In this function, the argument q will be dynamically defined, and the $.get method will return either true or false based on the data received from the Ajax call. <a href="any.php" class ...

Which is better for validation in Angular - $viewValue or $modelValue?

Being new to Angular, I am seeking validation on my form handling technique. Specifically, I want to notify the user with an appropriate message if they input more than 100 characters in a field. I am currently utilizing $viewValue for this purpose. Would ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...