same short circuit evaluation for multiple outputs

I am learning React and I have this short-circuit evaluation here:

  <button onClick={() => {
      index + 1 <= length && setSemiData(data[index + 1]);
      index + 1 <= length && setIndex(index + 1);
    }}
  >next</button>

Do I have to repeat the same ‘index + 1 <= length’ for both of them. Isn’t there some ‘better’ way to do it without repeating the same condition twice or multiple times?

Something like this code below:

    <button onClick={() => {
      index + 1 <= length && (setSemiData(data[index + 1]); setIndex(index + 1);)
    }}
    >next</button>

If the Title is misleading, I will change it if there are better suggestions.

Problem with Rounded progress bars in React

so i’m doing like a diet app that you put the meal, amount, its carb, protein and fat amount and it creates a list. And there’s a box where there’s three rounded progress bars, the active value is the percentage of each macronutrient, and the empty bar is the calories. And it is working fine, when i add something, the value goes 20%, add again, goes to 32%, if i take something out, it answer fine. The problem is that let’s i have 2 meals, one have 20g of carb, and the other have 0. When i added the first one, the bar went to let’s say 30%. When i added the other one, nothing happened. But if i remove de 20g carb meal, the value of the bar don’t change at all. Stays like that.

enter image description here

When i take off the second banana, the bar stays the same

enter image description here

I have the carb percentage

const carbPercentage = ((carbSum * 4 * 100) / calorieSum).toFixed(1);

And i tried the ternary operator at the value of the progress bar

<CircularProgressbar
            value={Number(carbPercentage) === 0 ? 1 : Number(carbPercentage)}
            maxValue={totalCarbBar}
            text={carbPercentage + "%"}
            styles={buildStyles({
              pathTransitionDuration: 1,
              pathColor: "#e5383b",
              textColor: "#242423",
              trailColor: "#333533",
            })}
          ></CircularProgressbar>

I deployed it, so you can check it out here https://macro-trackerreact.web.app/
And here’s the git repository https://github.com/JosephKorel/macro-count

Download PDF with 2 images and text on single button click using jsPDF

I am new to JavaScript and trying to add a button that exports a PDF with 2 images and some text on a on single button click.

Below is the code I currently have however, it only works when I double click the button.

How would I get this to work on a single click?

<div class="radarChartBox">
<canvas id="radarChart"></canvas>
<button id="downloadPDF" onclick="downloadPDF()">download PDF.</button>
</div>

<script>
function downloadPDF() {
const canvas = document.getElementById('radarChart');
const canvasImg = canvas.toDataURL('image/jpeg', 1.0);
const bannerImg = new Image;
bannerImg.src = "https://slipstreamgroup.com.au/wp-content/uploads/2022/03/Banner-img.jpeg";
    
let pdf = new jsPDF();
pdf.setFontSize(24);
pdf.setTextColor(255, 255, 255);
pdf.addImage(bannerImg, 'JPEG', 0, 0, 210, 55, "alias1");
pdf.text(10, 25, 'Your ' + formTitle);
pdf.addImage(canvasImg, 'JPEG', 10, 60, 190, 190, "alias2");
pdf.save(firmName + " " + formTitle + ".pdf");
}
</script>

How to check if textbox is empty and display a popup message

I am writing some code for a website to alert a user if any parameter in the textbox submission were left blank, and for some reason, it is not working. I’ve tried everything and I’m not sure if I am taking the right approach. Here is my javascript code:

let assetInfo = {
    asset_tag_no: $(`#asset_tag_no${i}`).val(),
    manufacturer: $(`#manufacturer_serial_no${i}`).val(),
    descriptions: $(`#description${i}`).val(),
    costs: $(`#cost${i}`).val(),
    po_no: $(`#p.o._no${i}`).val(),
    department_division_head: $(`#department_division_head${i}`).val(),
            }
        $('#submit').click(function(assetInfo){
        if($(assetInfo).val() == ''){
            alert('Input can not be left blank');
            }
        });

And here is my HTML:

<button type="button" class="btn btn-primary" id='submit'>SUBMIT</button>

Any tips?

Problem with import gcp secrets with node

I´m using gcp secrets manager (cloud service), and in my code I use the package @google-cloud/secret-manager to get them.

like this:

  const [version] = await client.accessSecretVersion({
    name: name_here
  })

    const responsePayload = Dotenv.parse(version?.payload?.data.toString());

    await this.setDatabase(responsePayload)

Well after that I use this functions setDatabase to put this payload on a config object, that I created more above in the code.

The problems is that, in other scripts, is imported that config object before the load of the setDatabase() in order to connect knex with dabatase, but in time of load the imports the config object is still blank.

Maybe somes pics will clarify:

config File

import in other script

console.log of config.database before loaded

console.log of config in other moment after loaded

Anyone has a tip for it?

React Material UI Select with Two columns

I need to use Material UI Select which shows a popover with two columns of checkboxes.

Problem – Material UI onChange handler value is “undefined” if MenuItem component is not a top tier child. I can not style the select to contain two column of MenuItems without adding a top tier div or box element.

Problem can be seen here where I wrap the MenuItem with div, then onChangeHandler for this item click has a value of undefined.

<Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
        >
          <div>
            <MenuItem value={10}>Ten</MenuItem>
          </div>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>

Problematic source code – https://codesandbox.io/s/basicselect-material-demo-forked-9ejyim?file=/demo.js:0-793

This is what I would like to achieve –enter image description here

Does anyone know any way around this?
Thanks!

How to combine array of objects into one object and then create another object within that array based on a condition on the index

I have an array of objects that i need to flatten/simplify/combine based on certain conditions. Here is the shape of my current array of objects below:

const arrayOfObjects = [
    {
        "Battery": "Battery"
    },
    {
        "batteryDetailsKey": [
            "Serial Number",
            "Type",
            "Part Number",
        ]
    },
    {
        "batteryDetailsVal": [
            "HJ3CA19347410218LJ98 100 QC",
            "Extended Range",
            "4P94-Q001",
        ]
    },
    {
        "Modules": "Modules"
    },
    {
        "moduleDetailsKey": [
            "Serial Number",
            "Part Number",
            "Cell Count",
        ]
    },
    {
        "moduleDetailsVal": [
            "83675327350061093222581609899001",
            "LJ98-10C779-A01",
            "32",
        ]
    },
    {
        "assetSeparator": "assetSeparator"
    },

    {
        "Battery": "Battery"
    },
    {
        "batteryDetailsKey": [
            "Serial Number",
            "Type",
            "Part Number"
        ]
    },
    {
        "batteryDetailsVal": [
            "HJ3CA19347410218LJ98 101 QC",
            "Extended Range",
            "4P94-Q002"
        ]
    },
    {
        "Modules": "Modules"
    },
    {
        "moduleDetailsKey": [
            "Serial Number",
            "Part Number",
            "Cell Count"
        ]
    },
    {
        "moduleDetailsVal": [
            "83675327350061093222581609899002",
            "LJ98-10C779-A02",
            "28"
        ]
    },
    {
        "moduleDetailsVal": [
            "83675327350061093222581609899003",
            "LJ98-10C779-A03",
            "27"
        ]
    },
    {
        "assetSeparator": "assetSeparator"
    },
    {
        "Battery": "Battery"
    },
    {
        "batteryDetailsKey": [
            "Serial Number",
            "Type",
            "Part Number",
        ]
    },
    {
        "batteryDetailsVal": [
            "HJ3CA19347410218LJ98 102 QC",
            "Extended Range",
            "4P94-Q003",
        ]
    },
    {
        "Modules": "Modules"
    },
    {
        "moduleDetailsKey": [
            "Serial Number",
            "Part Number",
            "Cell Count",
        ]
    },
    {
        "moduleDetailsVal": [
            "83675327350061093222581609899004",
            "LJ98-10C779-A01",
            "32",
        ]
    }
]

I basically want this arrayOfObjects to be shaped into this structure:

const shapeIWantArrayOfObjects = [
    {
        "Battery": "Battery",
        "batteryDetailsKey": [
            "Serial Number",
            "Type",
            "Part Number",
        ],
        "batteryDetailsVal": [
            "HJ3CA19347410218LJ98 100 QC",
            "Extended Range",
            "4P94-Q001",
        ],
        "Modules": "Modules",
        "moduleDetailsKey": [
            "Serial Number",
            "Part Number",
            "Cell Count",
        ],
        "moduleDetailsVal": [
            "83675327350061093222581609899001",
            "LJ98-10C779-A01",
            "32",
        ]
    },
    {
        "Battery": "Battery",
        "batteryDetailsKey": [
            "Serial Number",
            "Type",
            "Part Number"
        ],
        "batteryDetailsVal": [
            "HJ3CA19347410218LJ98 101 QC",
            "Extended Range",
            "4P94-Q002"
        ],
        "Modules": "Modules",
        "moduleDetailsKey": [
            "Serial Number",
            "Part Number",
            "Cell Count"
        ],
        "moduleDetailsVal": [
            "83675327350061093222581609899002",
            "LJ98-10C779-A02",
            "28"
        ],
        "moduleDetailsVal": [
            "83675327350061093222581609899003",
            "LJ98-10C779-A03",
            "27"
        ]
    },
    {
        "Battery": "Battery",
        "batteryDetailsKey": [
            "Serial Number",
            "Type",
            "Part Number",
        ],
        "batteryDetailsVal": [
            "HJ3CA19347410218LJ98 102 QC",
            "Extended Range",
            "4P94-Q003",
        ],
        "Modules": "Modules",
        "moduleDetailsKey": [
            "Serial Number",
            "Part Number",
            "Cell Count",
        ],
        "moduleDetailsVal": [
            "83675327350061093222581609899004",
            "LJ98-10C779-A01",
            "32",
        ]

    }
]

As you can see i’m basically wanting to combine the modules and batteries details into one object, then as you can see i want to create another object within that array once i hit the {"assetSeparator": "assetSeparator"}. That’s like my conditional that tells me that asset has been combined, now time to combine the next one, almost think of it as string.split("assetSeparator")

Can someone please tell me how i could achieve this, i’ve tried Object.assign({}, ...arrayOfObjects) but that didn’t quite achieve what i want, and i can’t detect the {"assetSeparator": "assetSeparator"} using the spread operator.

I’ve also tried doing a reduce arrayOfObjects.reduce(function(result, current) { return Object.assign(result, current); }, {}) but because it’s accumulating an object, it’s just override object properties with the same keys. Please help.

blocking my custom dropdown list

I have a custom dropdown list in the first el-collapse-item. When I expand the dropdown list, the list option is blocked by the second el-collapse-item.

<el-collapse v-if="currpage == 'edit'">

  <!-- 1st tab  -->
  <el-collapse-item class="collapseheader" title="Contact" name="1">
    <InputAutocomplete2
      :items="positionlist"
      :initval="cur_vendor.ContactPositionIDn2"
      :placeholder="$t('Position')"
      :key_field="'IDn'"
      :value_field="'PositionName'"
      @input="setinput_contactposition2" />
  </el-collapse-item>

  <!-- 2nd tab  -->
  <el-collapse-item class="collapseheader" title="Carrier" name="2">
    <!-- Some stuff here... -->
  </el-collapse-item>

</el-collapse>
<style>
.autocomplete2 {
    position: relative;
  }

  .autocomplete2-results {
    padding: 0;
    margin: 5px 0;
    border: 1px solid red;
    border-radius: 4px;
    height: 150px;
    overflow: auto;
    position: absolute;
    background-color: white;
    width: 100%;
    z-index: 999;
  }
  
  .autocomplete2-result {
    list-style: none;
    text-align: left;
    padding: 4px 2px;
    cursor: pointer;
  }

  .autocomplete2-result:hover {
    background-color: #4AAE9B;
    color: white;
  }
</style>

enter image description here

As shown in the picture above, the red border is my dropdown list options, and is being blocked by the 2nd tab. What I am trying to achieve is that the list would show on top of the 2nd tab.

I tried to play with CSS:property and CSS:z-index but no luck.
I also came across this post on StackOverflow element UI el-collapse in front if others components but there are some slight differences in our problem, hence the solution did not work for me.

Any suggestions? Thank you!

returned value undefined but not undefined right before returned. closure related? [duplicate]

Why is the returned value undefined when it looks fine right before it is return when I console log it. I assume it is something to do with closure but don’t get it. The code and the console logs for two different test calls are below:

CODE:

function addTogether() {
  const [a, b] = arguments;
  console.log(`a: ${a}  b: ${b}`);

  if (typeof a !== 'number') {
    return undefined;
    }
  if (b !== undefined){
    if (typeof b !== 'number'){
      return undefined;
    } else{
      let sum = a+b;
      console.log("sum being returned =", sum)
      return sum;
      }
  }
return ((b)=>{
  addTogether(a,b);
  })
}

console.log("returnVal =", addTogether(2,5));
console.log("returnVal =", addTogether(5)(7));

CONSOLE OUTPUT:
a: 2  b: 5
sum being returned = 7
returnVal = 7
a: 5  b: undefined
a: 5  b: 7
sum being returned = 12
returnVal = undefined

Building an web app to run inside other apps through a JS code-snippet

I was given the task to develop sliders/pop-ups for customers of the company I work for. This works a bit like chatbots (ie. Intercom). The user sees a small bubble on the bottom-right corner, clicks on it and it shows some information from our (Rails) app.

What’s the best way to create a javascript code to share with those clients? Should I add my code to a public js file and send those clients a script targeting my app? (like the example below?)

<script src='https://www.myapp.com/script.js'></script>

I’ve tried to do so, but it looks like the script doesn’t link to my CSS files, so styles are broken.

How to compare several rows between them on google app script

I have a google sheet with the following data
google sheet “formatfruit”

Each user has a fruit and a vegetable associated, I want to know the percentage of similarity between each user in the google sheet “fruit”
Today I can compare the first user kevin with all the others and return his compatibility percentage with all the other users in another google sheet called “matchofruit”.

I associated the value 1 when a user has a fruit or a vegetable in common with kevin and the value 0 if the user has no fruit or vegetable in common.
The result that appears in the google sheet matchofruit is here
google sheet matchofruit

The code I used is below

function myFunction() {
  var formafruit = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("fruit");
  var matchofruit = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("matchofruit");
  
  var n = formafruit.getLastRow(); 
  var user1 = formafruit.getRange(2,1).getValues();// name user 1 : kévin
  var user2 = formafruit.getRange(3,1).getValues();// name user 2 : mikael

    for (var i = 2;i<4;i++) { // i<4 because we have 3 column in formafruit
      for (var z = 2;z<n+1;z++) {
    matchofruit.getRange(z,1).setValue(user1); // Return the name of the users in the first column
    if(formafruit.getRange(2,i).getValue() === formafruit.getRange(z,i).getValue()){ // Compare the fruits and vegetables associated to kévin with the fruits and vegetables associated to each user
    matchofruit.getRange(z,i).setValue(1); // Returns 1 if kevin shares at least one fruit or vegetable in common with a user
      }
    else {
    matchofruit.getRange(z,i).setValue(0);
      } 
    }
  }
  
  // Calculate the % of common values
    for (var p = 0;p<n-1;p++){}
    for (var s = 0;s<n-1;s++) {
    var scoreforall = matchofruit.getRange(2,2,p,11).getValues()[s]// get the array of all the matches
    let sum = 0;
    for (let e = 0; e < scoreforall.length; e++) {
    sum += scoreforall[e]; // add each array together
    }
    var sumTotal= Math.round(sum*(100/2)); // convert in percentage each sum 
    matchofruit.getRange(s+2,4).setValue(sumTotal); //  send match values in column 4
   } 

  // Return the result in a sentence
    for (var a = 2;a<n+1;a++) {
    var usern = formafruit.getRange(a,1).getValues(); //get all the users' emails in the formafruit
    var valeurmatch = matchofruit.getRange (a,4).getValues(); // get value % of matches
    matchofruit.getRange(a,5).setValue("You have"+" "+valeurmatch+"%"+" "+"of values in common with"+" "+usern);//Return the % of common value between Kevin and the other users
    }    
    
}

I would like to be able to do the same for mikael, gauthier, vanessa and mireille knowing that I only put 5 users to simplify the problem but that in truth there can be more than 100 users and that each user has more than 11 associated fruits and vegetables. It’s been several weeks that I’m looking for a solution to my problem and I haven’t found anything to solve it. Do you have an idea?

Thanks!

Make API call to IPFS URI with `fetch` in javascript / typescript (Blocked by cors, network error, or type error)

I have a nextjs typescript project that needs to make the following fetch request:

        const tokenURIResponse = await fetch(
            "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json"
        )

This call returns a JSON object that looks like:

{
  "name": "PUG",
  "description": "An adorable PUG pup!",
  "image": "https://ipfs.io/ipfs/QmSsYRx3LpDAb1GZQm7zZ1AuHZjfbPkD6J7s9r41xu1mf8?filename=pug.png",
  "attributes": [
    {
      "trait_type": "cuteness",
      "value": 100
    }
  ]
}

However, I keep getting the following errors:

Brave:

Unhandled Runtime Error
TypeError: Failed to fetch

Source
components/NFTBox.tsx (85:39) @ _callee$

  83 | 
  84 |         // const tokenURIResponse = await fetch(tokenURI as string)
> 85 |         const tokenURIResponse = await fetch(
     |                                       ^
  86 |             "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json",
  87 |         )

Firefox:

Unhandled Runtime Error

TypeError: NetworkError when attempting to fetch resource.
Source

components/NFTBox.tsx (85:39) @ _callee$

  84 | 
> 85 |         const tokenURIResponse = await fetch(
     |                                       ^
  86 |             "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json",
  87 |         )

And when I look at the request in my debug tools, I see this:

Request URL: ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json
Referrer Policy: strict-origin-when-cross-origin
Provisional headers are shown
Learn more
Referer: http://localhost:3000/
User-Agent: XXXXXX

How do I fix this? I’ve seen questions talking about CORS and articles explaining cors but I’m not sure I follow what the suggestions are.

What do I need to do to make an API call to an IPFS node in my project?

returning multiple async functions in one function

I’m currently having probably an easy issue… where I have 2 async handlers I’m trying to combine into 1 async function :

async function unsubscribeUserHandler() {
    const unsubscribe = await fetch('/api/stripe-sessions/cancel-subscription', {
        method: 'PATCH',
        body: JSON.stringify(),
        headers: {
            'Content-Type': 'application/json',
        },
    });
    const data = await unsubscribe.json();
    if (!unsubscribe.ok) {
        Toast.fire({
            icon: 'error',
            title: `${data.message}`,
        });
    } else {
        Toast.fire({
            icon: 'success',
            title: `${data.message}`,
        });
    }
}

async function deleteUserHandler() {
    const deleteUser = await fetch('/api/user/delete-account', {
        method: 'DELETE',
        body: JSON.stringify(),
        headers: {
            'Content-Type': 'application/json',
        },
    });
    const data = await deleteUser.json();
    if (!deleteUser.ok) {
        Toast.fire({
            icon: 'error',
            title: `${data.message}`,
        });
    } else {
        Toast.fire({
            icon: 'success',
            title: `${data.message}`,
        });
    }
}

async function deleteAccount() {
    let res = null;
    try {
        res = await Promise.all([
            unsubscribeUserHandler(),
            deleteUserHandler(),
        ]);
        console.log('Success >>', res);
    } catch (err) {
        console.log('Fail >>', res, err);
    }
}


const Settings = () => {
return (

<DeleteAccount onDeleteAccount={deleteAccount} />
)
}

If I return them individually, it either deletes the account from DB or unsubscribes from stripe. But if I return the handler, it only deletes the ACC from db… not does both. Am I missing something?

Javascript – Trouble With Multiple Special Characters In String Replace

I have a long JSON string that, when parsed, is getting hung up on the following 3-character string: "{

I can’t seem to generate a Regular Expression (I seem to consistently struggle to understand RegEx’s) that searches for this string, since the itself keeps being interpreted as an escape character, and the " is looking for a matching, ending “.

e.g. I’ve been trying something like: string.replace('"{','');