Utilize Lodash to execute a class instance method only if the instance exists, and is not null or

Imagine we have a scenario like the one below:

class Individual {
  lastName: string;
  firstName: string;

  getCompleteName(separator: string) {
    return this.lastName + separator + this.firstName;
  }
}

const person = ...

const completeName = _.ifNotNull(person, value => value.getCompleteName('-'));

Does Lodash offer an alternative to the ifNotNull function which executes a method on the object parameter only if it is not null or undefined?

Answer №1

You have the option to utilize Lodash

Indeed, Lodash offers the specific function you are seeking, it's known as _.invoke. In the scenario mentioned earlier, you can implement it like this:

const fullName = _.invoke(person, "getFullName", "-");

And it will perform as expected. So, how does _.invoke function?

  • The signature of _.invoke is: _.invoke(object, path, [args]). It triggers the method at the specified path (which could be a nested path or just the method name) within the object, with binding to the object for this.

Can I experiment quickly in the browser?

Certainly! I have set up a Codepen where you can directly test this and other methods to achieve the same outcome straight from your browser. Just ensure to access the browser console to view the test outcomes! Here is the link, look for _.invoke in testcase1a() and testcase1b():

https://codepen.io/jhack_jos/pen/ExNVbWp

How is the expression resolved above?

  1. If person is undefined or doesn't contain a method named getFullName, then the expression
    _.invoke(person, "getFullName", "-");
    resolves in this manner:
    //STEP 1
    const fullName = _.invoke(person, "getFullName", "-");

    //STEP 2
    const fullName = undefined;
  1. If person is defined and has the method getFullName:
    //STEP 1
    const fullName = _.invoke(person, "getFullName", "-");

    //STEP 2
    const fullName = person.getFullName("-");

    //STEP 3
    const fullName = "surname-firstname";

Warning

If person possesses a property that is not a method named getFullName, you'll encounter a runtime error!!

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 best way to extract age data from an Angular form group function and save it to the back-end?

I stumbled upon an interesting function in another post that checks whether a person is 18 years old or older. I would like to convert and store the age in the backend separately, but the challenge is that I don't have an age input in the HTML. Here&a ...

An issue arises in Slate.js when attempting to insert a new node within a specified region, triggering an error

A relevant code snippet: <Slate editor={editor} value={value} onChange={value => { setValue(value); const { selection } = editor; // if nothing is currently selected under the cursor if (select ...

What is the proper way to utilize bootstrap dropdown menus?

I need to create a dropdown menu similar to the one shown in this image: https://i.sstatic.net/SXDgy.png https://i.sstatic.net/wVbnd.png I attempted to use code from the following URL: https://getbootstrap.com/docs/4.0/components/dropdowns/, but unfortun ...

Leverage local JSON file data in HTML using TypeScript and Angular 7 for enhanced functionality

I am looking to incorporate a basic local JSON file into my Angular 7 project and utilize the data within my HTML file. Just a straightforward example. The JSON file is named data.json. I aim to retrieve the information from this JSON file in app.component ...

Executing a child component function once the parent component data is loaded in Angular 5

In my project, I have a parent component called program-page.component where I am invoking a function to fetch some data. ngOnInit() { this.getProgress(); } getFirstProgramItem() { this._contentfulService.getProgramItem(4, 1) .then((programItem) = ...

Encountering crashes while initializing the router in the constructor of a service in Angular 4.3

I've been scratching my head over this problem. It seems like I'm overlooking something simple. Let me show you what's inside my home.component.ts file: import { Component, OnInit } from '@angular/core'; import { AuthService } f ...

Show an array of arrays using a visual table representation

I am working with an Array of arrays in my data, and they are structured like this : https://i.sstatic.net/3grh6.png Now, I am trying to showcase this array in a table, but all I am getting is a blank page. Here is the HTML code for the table (I have incl ...

The function within filereader.onload is not running properly in JavaScript

When working with FileReader to read a file and convert it to base64 for further actions, I encountered an issue. Although I was able to successfully read the file and obtain its base64 representation, I faced difficulties in utilizing this data to trigger ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

Module not located following the completion of project compilation

Below is the content of my package.json file: { "main": "./build/app.js", "types": "./build/app.d.ts", "scripts": { "start": "tsc && node build/app.js", "dev": "concurrently \"tsc -w \" \"nodemon ...

Implement endless scrolling to JSON dataset in an ionic-3 application

Is there a way to incorporate infinite scroll into my JSON array while initially displaying only 5 items? data:[ 0: Object { id: 123, title: "New family member Khjkjh has joined mymily", mm_family_id: 122, … } 1: Object { id: 124, title: "New family mem ...

bringing TypeScript functions into another file

I am attempting to include a function in my main.ts file, but I keep encountering errors like 'is not a module' or 'unexpected import token' when I try to execute my file using node main.ts. These functions are not part of any node mod ...

Transform "<Mutation>" to useMutation

In my removeUser page, I have implemented a < Mutation > and handled errors using the submitForm() function. The initial code worked perfectly: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); con ...

In need of secure HTML, received a dose of Style instead

I am currently developing a component that loads html content dynamically and validates the loaded styles to prevent any mixing of app styles with the dynamic template's styles. This is the structure of my HTML component: <div class="modal-header ...

Can builtins like DOM globals be explicitly imported?

The present situation includes the utilization of rollup (as well as iife parameters), but I am hesitant about whether it is solely related to rollup or typescript. My objective is to achieve something similar to this: import { document } from "[wherever ...

Is there a way to merge TypeScript code with C++ during compilation?

Currently, I have a project written entirely in C++. However, there is an additional file written in typescript because I couldn't find equivalent libraries in C++. This typescript file performs the following actions: It contains a typescript CLI cod ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Narrowing down types within an array of objects

I am encountering an issue with the following code snippet: const f = (x: unknown) => { if (!x || !Array.isArray(x)) { throw new Error("bad"); } for (const y of x) { if (!y || typeof y !== "object") { throw new E ...

Tips for retrieving the Solana unix_timestamp on the front-end using JavaScript

Solana Rust smart contracts have access to solana_program::clock::Clock::get()?.unix_timestamp which is seconds from epoch (midnight Jan 1st 1970 GMT) but has a significant drift from any real-world time-zone as a result of Solana's processing delays ...