How do I group multiple functions within one class in JavaScript?

My JavaScript class module file contains multiple functions of various categories, such as file-operation related ones and string-processing related ones.

class App {
  static fileFunc1() {
    ...
  }

  static fileFunc2() {
    ...
  }

  static strFunc1() {
    ...
  }

  static strFunc2() {
    ...
  }
}

I wanted to categorize these functions within ONE FILE so that they can be called as a chained string as follows.

App.file.fileFunc1();
App.str.strFunc2();

After some trials and errors, I found the solution by myself as described below.

class App {
  /**
   * Group of file-operation related functions
   */
  static file {
    fileFunc1: () => {
      ...
    },

    fileFunc2: () => {
      ...
    }
  };

  /**
   * Group of string-processing related functions
   */
  static str {
    strFunc1: () => {
      ...
    },

    strFunc2: () => {
      ...
    }
  };
}

Is this the recommended way to achieve my needs?
Or are there any other recommended solutions or smart ideas?

[Additional remarks]

There is one thing I have to mention that I don’t want to divide those functions into multiple files because there are already many generic module files and increasing the number of files is not welcome.

How can I attach the correct JSON fetch results to their corresponding container divs?

I’m trying to display a table of events from a JSON fetch – it mostly works as is, the only thing I’m struggling to figure out is how do I attach the correct events to be listed with their corresponding competition titles.

The result I’m getting right now are wrong as:
the first competition shows all of the fetched competitions’ matches,
the second one shows all matches except the first ones’,
the third competition shows all of the matches except the first and the seconds’
and so on.

As the below code shows I’m creating a wrapping div and a ‘p’ for the competition title, and after that I’m attaching the events (esports matches):

function appendData(data) { 
  var mainContainer = document.querySelector('.calendar-list');
  for (var i = 0; i < data.competitions.length; i++) {
    mainContainer.innerHTML += `<div><p class="event">` + data.competitions[i].name + `</p></div>`;
    for (var j = 0; j < data.competitions[i].events.length; j++) {
      for (var x of document.querySelectorAll('.calendar-list>div')) { x.innerHTML += `<p class="match"><span>` + data.competitions[i].events[j].home.name + `</span><span>` + data.competitions[i].events[j].away.name+ `</span><span>` + data.competitions[i].events[j].cutoffTime.slice(11, 16) + `</span></p>`;
      }
    } 

  }
}

the html structure of the list (with 2 competitions and a few events/matches) looks like this (except in reality the events are not sorted correctly):

<div class="calendar-list">
    <div>
        <p class="event">World Cup</p>
        <p class="match"><span>Cloud9 White Cloud</span><span>Guild X</span><span>17:00</span></p>
        <p class="match"><span>G2 Gozen</span><span>Liquid Brazil</span><span>17:00</span></p>
        <p class="match"><span>Cloud9</span><span>Guild X</span><span>17:00</span></p>
        <p class="match"><span>G2 Gozen White</span><span>Liquid Brazil</span><span>17:00</span></p></div>

    <div>
        <p class="event">Champions Tour: Game Changers Championship</p>
        <p class="match"><span>Cloud9 White</span><span>Guild X</span><span>17:00</span></p>
        <p class="match"><span>G2 Gozen</span><span>Liquid Brazil</span><span>17:00</span></p>
    </div>

</div>

How do I display only the matches that are inside each competition for their list view?

Make other block disappear when chose multiple values

How can I make other filter button disappear when picked 1 (or multiple) value in same filter block.

Here is my code base:

const FilterBlock = props => {
    const {
        filterApi,
        filterState,
        filterFrontendInput,
        group,
        items,
        name,
        onApply,
        initialOpen
    } = props;

const { formatMessage } = useIntl();
const talonProps = useFilterBlock({
    filterState,
    items,
    initialOpen
});
const { handleClick, isExpanded } = talonProps;
const classStyle = useStyle(defaultClasses, props.classes);
const ref = useRef(null);

useEffect(() => {
    const handleClickOutside = event => {
        if (ref.current && !ref.current.contains(event.target)) {
            isExpanded && handleClick();
        }
    };
    document.addEventListener('click', handleClickOutside, true);
    return () => {
        document.removeEventListener('click', handleClickOutside, true);
    };
}, [isExpanded]);

const list = isExpanded ? (
    <Form>
        <FilterList
            filterApi={filterApi}
            filterState={filterState}
            name={name}
            filterFrontendInput={filterFrontendInput}
            group={group}
            items={items}
            onApply={onApply}
        />
    </Form>
) : null;

return (
    <div
        data-cy="FilterBlock-root"
        aria-label={itemAriaLabel}
        ref={ref}
    >
        <Menu.Button
            data-cy="FilterBlock-triggerButton"
            type="button"
            onClick={handleClick}
            aria-label={toggleItemOptionsAriaLabel}
        >
            <div>
                <span>
                    {name}
                </span>
                <svg
                    width="8"
                    height="5"
                    viewBox="0 0 8 5"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                >
                    <path
                        d="M6.97291 0.193232C7.20854"
                        fill="currentColor"
                    />
                </svg>
            </div>
        </Menu.Button>
        <div>
            <div>
                {list}
            </div>
        </div>
    </div>
);
};

I am trying to achieve when I chose 1 value or more than 1 value inside filter block the other block will disappear but right now I achieved that when I chose 1 value the other filter block disappear but when I chose another value in the same block the other filter block appear again. Anyone have idea how can I work on this?

I am using React and Redux for this project

Thank you for helping me on this!!!!

enter image description here

Update:

Added parent component for FilterBlock.ks:

const FilterSidebar = props => {
    const { filters, filterCountToOpen } = props;
    const [selectedGroup, setSelectedGroup] = useState(null);
    const talonProps = useFilterSidebar({ filters });
    const {
        filterApi,
        filterItems,
        filterNames,
        filterFrontendInput,
        filterState,
        handleApply,
        handleReset
    } = talonProps;

    const filterRef = useRef();
    const classStyle = useStyle(defaultClasses, props.classes);

    const handleApplyFilter = useCallback(
        (...args) => {
            const filterElement = filterRef.current;
            if (
                filterElement &&
                typeof filterElement.getBoundingClientRect === 'function'
            ) {
                const filterTop = filterElement.getBoundingClientRect().top;
                const windowScrollY =
                    window.scrollY + filterTop - SCROLL_OFFSET;
                window.scrollTo(0, windowScrollY);
            }

            handleApply(...args);
        },
        [handleApply, filterRef]
    );

    const result = Array.from(filterItems)
        .filter(
            ([group, items]) =>
                selectedGroup === null ||
                selectedGroup === filterNames.get(group)
        )
        .map(([group, items], iteration) => {
            const blockState = filterState.get(group);
            const groupName = filterNames.get(group);
            const frontendInput = filterFrontendInput.get(group);

            return (
                <FilterBlock
                    key={group}
                    filterApi={filterApi}
                    filterState={blockState}
                    filterFrontendInput={frontendInput}
                    group={group}
                    items={items}
                    name={groupName}
                    onApply={(...args) => {
                        console.log('args: ', ...args);
                        setSelectedGroup(prev =>
                            prev !== null ? null : groupName
                        );
                        return handleApplyFilter(...args);
                    }}
                    initialOpen={iteration < filterCountToOpen}
                    iteration={iteration}
                />
            );
        });

    return (
        <div className="container px-4 mx-auto">
            <Menu
                as="div"
                className="my-16 justify-center flex flex-wrap py-5 border-y border-black border-opacity-5"
            >
                {result}
            </Menu>
        </div>
    );
};

‘get’ method of descriptor object of class method in javascript

I am learning typescript on Udemy and the instructor is going through the method decorator to try to bind a method to the instance when it invoked in a event listener.

The way he did is to use decorator in TypeScript and amend the Property Descriptor.

Code is shown below.

function Autobind(_: any, _2: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    console.log(descriptor)
    console.log(originalMethod)
    const adjDescriptor: PropertyDescriptor = {
        configurable: true,
        enumerable: false,
        get() {
            const boundFn = originalMethod.bind(this);
            return boundFn;
        }
    }
    console.log(adjDescriptor)
    return adjDescriptor;
}

class Printer {
    message = 'This works!';

    @Autobind
    showMessage() {
        console.log(this.message);
    }
}

const p = new Printer();

const button = document.querySelector('button')!;
button.addEventListener('click', p.showMessage);

I have two questions on his method.

  1. How the ‘get’ method of the property descriptor get invoked in this case?
  2. Originally the descriptor has a value property which is the showMessage method. I am curious why he did not amend the value property. Instead, he is adding the get method to the descriptor and ignore the value property.

Wait until the page is fully loaded before downloading it with got in NodeJS [duplicate]

I want to retrieve automaticly the text from a getpaste.link. I’m fine with parsing but I need to wait until the page made it’s server request to get the plaintext.

i.e.
I use got in NodeJS to get html from a page.
I get this :
loading getpastlink page
Because it doesn’t want until I get this:
loaded getpastlink page

I’ve searched up on the documentation for anytype of delays but I didn’t find anything.

How to use aws s3 createPresignedPost with ksm encryption

I have found aws documentation for doing this with Java, and a couple of scattered references for javascript developers, but I have not been able to accomplish this without receiving access denied from aws. I’ve tried a lot of different variations.

To make matters a little worse, my development environment is a proprietary framework that handles a lot of the role and credentialling in the background, but I have been able to identify that the ksm policy is the sticking point, and I have not found the solution.

I’ve tried passing parameters to the signing process:

const params = {
    Bucket: targetBucket,
    ServerSideEncryption: 'aws:kms',
    SSEKMSKeyId: keyId,
    Conditions: [{ acl: 'private' }, { key: filepath } ]
};
return new Promise((res, rej) => {
    clientS3.createPresignedPost(params, (err, data) => {
        if (err) {
            console.log(err.message);
            rej(err);
        } else {
            console.log(data);
            res({ data, filepath, encryption, bucket });
        }
    });
});

That didn’t work. Access denied. (Yes, I included these values in the formdata, to ensure a correctly signed request.)

I also tried adding headers to the post request itself, via:

return axios
  .post(response.data.url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'x-amz-server-side-encryption-aws-kms-key-id': response.encryption,
      'x-amz-server-side-encryption-context': bucketArn
    },
    ....

Access Denied. I’ve tried mixing and matching approaches. I can make things worse by breaking the signature, but I can’t land the encrypted file or find documentation to accomplish this.

node.js : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client – [duplicate]

After i do one post, the second time i try it gives me this error.

My post trys to send a json file as response, after a file is edited, it works the first time, the second time i do a post without closing the server stops working. If i restart de server it works again.

app.post("/data3", upload.array("files"), uploadFiles);

function uploadFiles(req, res) {
    fs.watchFile(

      "./data/results.json",
      
      {
        bigint: false,
      
        persistent: true,
      
        interval: 4000,
      },
      (curr, prev) => {
        console.log("nThe file was edited");
      
        console.log("Previous Modified Time", prev.mtime);
        console.log("Current Modified Time", curr.mtime);
        
        res.json(fs.readFileSync("./data/results.json", "utf8"));

        console.log(
          "The contents of the current file are:",
          fs.readFileSync("./data/results.json", "utf8")
        );
      }
    );
}

React typescript eslint error Parsing error: Unexpected token ! How to fix this?

So this is my index.tsx:

import React from 'react';
import { createRoot } from 'react-dom/client';

import App from './App';


const container = document.getElementById('root')!;
const root = createRoot(container);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);


and this is my eslintrc.js:

module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: ['plugin:react/recommended', 'prettier'],
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      parserOptions: {
        project: ['./tsconfig.json']
      }
    }
  ],
  parserOptions: {
    parser: 'babel-eslint',
    ecmaFeatures: {
      jsx: true
    },
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  plugins: ['react', '@typescript-eslint', 'prettier', 'simple-import-sort'],

i have tried to install babel-eslint, and add it like a parser? but it didin`t help

so here`s the question, how to solve the problem “error Parsing error: Unexpected token !”?

How to get multiple urls api call in one file in javascript?

Hello StackOverflow Comunity, I am working on one android app which is html based gui and the problem is I want to fetch data from the api the problem is I have two parameters which uses different url to fetch data.

`

$(document).ready(function() {
    //role = localStorage.getItem("role");
    //u_name = localStorage.getItem("name");
    //$("#u_name").text(localStorage.getItem("name"));
    //$("#role").text(localStorage.getItem("role"));
    //$(".profile_image").prop("src", localStorage.getItem("profile_image"));
    //$("#main_wallet").text("₹ " + localStorage.getItem("wallet"));
    $('#app_name').text(localStorage.getItem("app_name"));
    base_url = localStorage.getItem("base_url");
    mobile = localStorage.getItem("mobile");
    password = localStorage.getItem("password");
    localStorage.setItem("prepaidSelectMountPrice", '');
    localStorage.setItem("DthSelectMountPrice", '');
    localStorage.setItem("numberEntered", "");
    localStorage.setItem("ProviderSelected", "");
    localStorage.setItem("stateSelected", "");

    $('#loader').attr('style', '');
    $.ajax({
        url: base_url + "api/android_app/home_data",
        type: "post",
        data: { mobile: mobile, password: password },
        success: function(res) {
            $('#loader').attr('style', 'opacity: 0.03125; display: none;');
            if (res.error == 0) {
                $('#main_wallet').text("₹ " + res.wallet_balance);
                $('#news_text').html(res.announcement);
                localStorage.setItem("upi_status", res.upi.status);
                localStorage.setItem("upi_VPA", res.upi.upi_id);
                localStorage.setItem("upi_minimumAmount", res.upi.minimum_amount);


                jQuery.each(res.sliders, function(j, value) {
                    html = '<img class="mySlides" src="' + base_url + 'slider_image/' + value.image + '" style="height:150px;width:100%;border-radius: 10px 10px 10px 10px !important;">'
                    $('#splide01').append(html);
                });
                carousel();
            }

        },
        complete: function() {}
    });
    
    $("#home_refresh").on("click", function() {
        $('#loader').attr('style', '');
        $.ajax({
            url: base_url + "api/android_app/home_data",
            type: "post",
            data: { mobile: mobile, password: password },
            success: function(res) {
                $('#loader').attr('style', 'opacity: 0.03125; display: none;');
                if (res.error == 0) {
                    $('#main_wallet').text("₹ " + res.wallet_balance);                    
                    $('#news_text').html(res.announcement);

                    $('#splide01').empty();
                    jQuery.each(res.sliders, function(j, value) {
                        html = '<img class="mySlides" src="' + base_url + 'slider_image/' + value.image + '" style="height:150px;width:100%">'
                        $('#splide01').append(html);
                    });
                    carousel();
                }

            },
            complete: function() {}
        });
    })
})

var myIndex = 0;

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) { myIndex = 1 }
    x[myIndex - 1].style.display = "block";
    setTimeout(carousel, 5000); // Change image every 2 seconds
}


//alert();
var role_id = localStorage.getItem("role_id");
if (role_id != '6') {
    $('#manage_h6').show();
    $('#manage_1').show();
    $('#manage_2').show();
    $('#manage_3').show();
    $('#manage_4').show();
    //alert("retailer");
}

`

This is where the home screen fetches wallet balance now I want to fetch total recharges and and total commission which is in another url `


base_url = localStorage.getItem("base_url");
mobile = localStorage.getItem("mobile");
password = localStorage.getItem("password");
$('#loader').attr('style','');
        $.ajax({
            url: base_url + "api/android_app/day_book_reports",
            type: "post",
            data: {mobile:mobile,password:password},
            success: function (response) {
                
                var result = JSON.parse(JSON.stringify(response));
                //console.log();           
                $('#tr_success_amount').text("₹ "+result.reports.tr_success_amount);              
                $('#tr_commission').text("₹ "+result.reports.tr_commission);
              
                
                $('#loader').attr('style','opacity: 0.03125; display: none;');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            },
        });

`

How I can merge this two different urls to show data on home screen. Please guide me

I have try others but it didn’t work for me, please guide me

How can I show the result of between the subtraction of vectors?

I am trying to show the result of between the subtraction of vector 1 and vector 2, how can I do this?

So I have been trying to declare four variables (vector, vector2, vector3 and subtraction).

The subtraction will receive the result of the subtraction between five numbers of vector and five numbers of vector 2, after that the vector 3 will show these results on the screen.

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>exer8vetor.com</title>
</head>
<body>
      <h4>Digite 5 números para o primeiro vetor</h4>
      <form action="">
        <label>Digite o numero 1:</label>
        <input type="number" id="0" name="number1"><br>
        <label>Digite o numero 2:</label>
        <input type="number" id="1" name="number2"><br>
        <label>Digite o numero 3:</label>
        <input type="number" id="2" name="number3"><br>
        <label>Digite o numero 4:</label>
        <input type="number" id="3" name="number4"><br>
        <label>Digite o numero 5:</label>
        <input type="number" id="4" name="number5"><br>

        <h4>Digite 5 números para o segundo vetor</h4>
      <form action="">
        <label>Digite o numero 1:</label>
        <input type="number" id="5" name="number6"><br>
        <label>Digite o numero 2:</label>
        <input type="number" id="6" name="number7"><br>
        <label>Digite o numero 3:</label>
        <input type="number" id="7" name="number8"><br>
        <label>Digite o numero 4:</label>
        <input type="number" id="8" name="number9"><br>
        <label>Digite o numero 5:</label>
        <input type="number" id="9" name="number10"><br>
        

        <input type="button" onclick="coletarNumeros()" value="Enviar">
      </form>

  <script>
        var vetor = new Array(5);
        var vetor2 = new Array(5);
        var vetor3 = new Array (5);
        var subtracao = 0

            function coletarNumeros(){
                for(posicao = 0; posicao < vetor.length; posicao++)
                {
                    vetor[posicao]=document.getElementById(posicao).value;
                } 
                for (posicao2 = 0; posicao2 < vetor.length; posicao2++)
                {                                                     
                    vetor2[posicao]=document.getElementById(posicao).value;
                }
                for (posicao3 = 0; posicao3 < vetor.length; posicao3++)
                {                                                     
                    subtracao = vetor[posicao] - vetor2[posicao]
                    vetor3[posicao] = subtracao
                    document.write("Este é um dos valores do vetor 3: ", vetor3[posicao], "<br>")
                    
                }

                    
                }
    </script>
</body>
</html>

Title with javascript and slice property

I’m currently working on a project with a Radio Api that we made. I was working with javascript and I wanted to create a fadeout title that makes the last 2 letters of a song fade out. I ended up with something like:

let srt =  document.getElementById('songTitle');
if(srt.length > 20)
{
 let sliced = srt.slice(-2);
 sliced.style.opacity = '1';
}

This code didn’t work at all, so I tried another approach to the code and made a css style with the classname of “.FadeOut”.
Then changed the javascript with:

let srt =  document.getElementById('songTitle');
if(srt.length > 20)
{
 let sliced = srt.slice(-2);
 sliced.classList.add(".FadeOut");
}

Still, the code is not working. Then I tried to see if in the console.log the slicing of the last 2 letters was doing it right, and yes, the console gives me the last 2 letters of the title I’m working on…
Any suggest would be great!!
Thanks!

Error , I don’t know why this doesn’t work

<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”utf-8″>
<title>Error</title>
</head>

<body>
<pre>Cannot DELETE /api/pets/delete-pet/638d04a85116531943a6185a</pre>
</body>

  exports.deletePet = (req, res) => {


    Pet.findByIdAndDelete(req.params.id)
     .then((pet) => {
       if (!pet) {
         res.status(400).send({
             status: ' not found'
         });
       } else {
         res.status(200).send({
             status: "succes"
         });
       }
     })
     .catch((err) => {
       console.error(err);
       res.status(500).send('Error: ' + err);
     });

  };

what i expect :

{ status: “succes” }