Conditionally importing JS library

In my Rails 6.x app, I was using Webpacker in order to compile my styles and transpile my JS.

As part of my apps upgrade to Rails 7, I scrapped Webpacker (as it’s no longer recommended) and switched over to the new cssbundling-rails and jsbundling-rails gems.

These are super fast and sooo much easier to use.

However, I just ran a Lighthouse report on my site and I think certain pages on my site are loading all my JS even though a lot of it is not even executed on most pages.

For example I have a script that plays audio using the Plyr library on one page.

My script for this, at the top has an import like:

import Plyr from 'plyr'

I’ve tried to conditionalism this by checking if a specific element exists on the page first before importing but it didn’t like that.

How can I only perform some of these imports when they are necessary and not when they are not.

How do I convert the above to be conditional?

Thanks,
Neil

How do I Wait With Extends Script (Adobe)

i’m currently working on an extends script which is the technology that we can use to create extension for adobe softwares, its a javascript similar script language
Im working on a script to automate some boring and repetitive tasks

Here is my problem i’ve to wait the creation of a bin before use a variable which call this bin but i can’t, i tried

.then( Promise => { //Some Code }) ; setTimeout(Function(), time); nothing is working

Can someone help me please ?
Here is my code

    root = app.project.rootItem
    newFilesPath = "Path"
    newFilesBin = root.children[0]
    
    app.project.importFiles(newFilesPath, true, newFilesBin, false)
    
    app.project.save()
    
    for(i=0; i<newFilesBin.children.numItems; i++){  //here is the problem it tells me that
        newFile = newFilesBin.children[i]            //newFilesBin is null, i think he has not the 
                                                     //time to create the file and then to put it 
                                                     //in the variable
        name = newFile.name
    
        newTiktokBin = root.createBin(name)
    
        root.children[i].children[0].moveBin(newTiktokBin)
    }

forEach and assign to variable

This is just an example that I want to understand. I know there is a better way to select the last element from the array, but I don’t know why it works that way.

const numbers = [1, 2, 3];

let exampleId: number;

numbers.forEach(function(number) {
  exampleId = number;
});

console.log(exampleId);

Why do I get the error “Variable ‘exampleId’ is used before being assigned.” in the line from console.log?

Understanding IIFE and why it’s necessary here

In the IIFE docs on MDN, it talks about using IIFE’s for:

We would also use IIFE to create private and public variables and methods.

And it gives this example:

const makeWithdraw = balance => (function(copyBalance) {
  let balance = copyBalance; // This variable is private
  let doBadThings = function() {
    console.log("I will do bad things with your money");
  };
  doBadThings();
  return {
    withdraw: function(amount) {
      if (balance >= amount) {
        balance -= amount;
        return balance;
      } else {
        return "Insufficient money";
      }
    },
  }
})(balance);

const firstAccount = makeWithdraw(100); // "I will do bad things with your money"
console.log(firstAccount.balance); // undefined
console.log(firstAccount.withdraw(20)); // 80
console.log(firstAccount.withdraw(30)); // 50
console.log(firstAccount.doBadThings); // undefined; this method is private
const secondAccount = makeWithdraw(20); // "I will do bad things with your money"
console.log(secondAccount.withdraw(30)); // "Insufficient money"
console.log(secondAccount.withdraw(20));  // 0

However, I don’t understand at all why an IIFE is necessary here. It seems the exact same thing can be done with:

  function makeWithdraw(copyBalance) {
      let balance = copyBalance;
      let doBadThings = function() {
        console.log("I will do bad things with your money");
      };
      doBadThings();
      return {
        withdraw(amount) { return (balance < amount) ? "Insufficient money" : (balance -= amount, balance)}
      }
  }


  const firstAccount = makeWithdraw(100); // "I will do bad things with your money"
  console.log(firstAccount.balance); // undefined
  console.log(firstAccount.withdraw(20)); // 80
  console.log(firstAccount.withdraw(30)); // 50
  console.log(firstAccount.doBadThings); // undefined; this method is private
  const secondAccount = makeWithdraw(20); // "I will do bad things with your money"
  console.log(secondAccount.withdraw(30)); // "Insufficient money"
  console.log(secondAccount.withdraw(20));  // 0

Is there something I’m missing here in what the IIFE does here that the normal function would not, or why is this used as an example? I understand the concept of closures, but couldn’t a closure just as easily be accomplished with:

'use strict';
function closure() {
  console.log('init closure...');
  let privateVar = 1;
  return {
    func1() {console.log('func1...')},
    func2() {console.log('func2...')},
  }
}
let f = closure();
f.func1();
f.func2();
f.privateVar; // undefined

Converting Typed Properties in Javascript Classes

Just starting to use Javascript Classes and have a quick question. In the example below, I want to ensure/convert certain properties to be numeric when I create the class. For instance, if the user enters “$10.50” for the unit price, I want the class to only have 10.50 so the total function works. I’m sure this can be done with a getter/setter but I can’t quite figure out how to implement it.

<form name="orderform">
  order date: <input name="order_date" value="" type=text>
  <br>item_name: <input name="item_name" value="" type=text>
  <br>unit_price: <input name="unit_price" value="" type=text>
  <br>quantity: <input name="quantity" value="0" type=text>
</form>

...

class OrderItem {
  constructor(
    order_date,
    item_name,
    unit_price,
    quantity,
  ) {
    this.order_date = order_date;
    this.item_name = item_name;
    this.unit_price = unit_price;
    this.quantity = quantity;    
  }
  get total() {
    return this.unit_price * this.quantity;
  }
}


const orderitem1 = new OrderItem();



function GetNumber(val)
{
  if (typeof val !== 'undefined')
  {
      return Number(val.replace(/[^0-9.-]+/g, ""));
  }
  else
  {
    return 0;
  } 
}



function getOrder()
{
  $("#orderform").serializeArray().map(function(x){orderitem1[x.name] = x.value;}); 
  
  var total = orderitem.total;  //doesn't work if they enter '$10.50'

//...do stuff here with the orderitem1 class....
}

How to combine position fixed modal with locomotive scroll?

Question only for locomotive scroll experts
I have container inside of which I’ve put everything which I have, all the blocks like footer and all other things.
After this data-section I’ve put my fixed modal Here You can check how it looks as a structure

But the main problem – when I’m opening this modal and then close it.
Locomotive creates blank space with exact height of this modal. Anyone know how to fix that?

Longest Common Prefix destructuring issue?

I solved this problem in VSCode but it doesn’t work in Leetcode. Anyone know why?

var longestCommonPrefix = function(strs) {
    const a = strs[0];
    const b = strs[1];
    const c = strs[2];
    let count = 0;
    let ans = '';
    for (let i = 0; i < a.length; i++) {
        if (a[i] === b[i] && a[i] === c[i]) {
           count++;   
        } else {
            continue;
        }
    }
    ans = a.substring(0, count);
    return ans;
};

P5.js – createGraphics() leads to strange results with small screen size

I’ve been trying to solve this problem for days. I simplified the problem with this simple code :

let graphicCanvas
let ctx
let speed = 1
function setup(){
    cnv = createCanvas(windowWidth, windowHeight)
    cnv.style('display', 'block');
    graphicCanvas = createGraphics(800,800)
    ctx = graphicCanvas.canvas.getContext('2d')
    
}
function draw(){
    ctx.drawImage(ctx.canvas,0,0,800,800,0,speed,800,800)

    graphicCanvas.noStroke()
    graphicCanvas.fill(255,0,0)
    graphicCanvas.circle(100,100,50)
    image(graphicCanvas,0,0)
    
}

This code is supposed to show the trails,of a red circle, that is getting longer after each loop:
Red trails

The problem is that this code only works on large screens. With small screens I end up with this result : Red circles

I don’t know if the problem comes from the createGraphics(), the drawImage() or the image().

I already tried to use graphicCanvas.push() and graphicCanvas.pop() but nothing change. How can I get the “Red trails” result for every screen size ?

(As a foreigner, please excuse me for the english mistakes)

Update the channel name several times

What I am trying to do is have a counter that is shown in the name of a channel.

I am aware of the Discord API rate-limits and that I can change the channel name 2 times in 10 minutes. I am aware that DiscordJS handles rate-limits internally by putting them in a queue.

The problem is right here, suppose the bot executes these lines consecutively:

myChannel.setName(1);
myChannel.setName(2);
myChannel.setName(3);
myChannel.setName(4);
myChannel.setName(5);

What happens is that the first two requests change the channel name and the other three go to queue. But after 10 minutes what happens is that the third and fourth requests are sent, while I would like to jump to the last one instead.

I was interested in finding out if there was a way to check the response to the request for a channel name change, in order to “intercept” the rate-limit and prevent it from going into the queue.

I have already thought of a solution for the problem itself:

setInterval(()=>{
    myChannel.setName(varDefSomewhereElse);
},10*60*1000);

but I want to solve the “problem” as efficiently as possible.

Storing Access & Refresh tokens from multiple Providers?

Say I am allowing my users to connect to Facebook, Instagram, Pinterest & Twitter, so they can use their API’s. So I get access tokens for all those providers.

From what I’ve read, my inclination now is to store them in a http-only cookie.

However, with 4 access tokens, would that mean that all 4 access tokens are always being sent on every request?

What would be a secure approach here? Or would I in this case not store them on the client at all?

I’m newbie here. What are the mistakes in my code? [closed]

It’s keep giving me the same result. Showing both ‘andy’ and ‘sara’ poor regardless of their money. Please tell me where I’m wrong.

function persona(firstName, amount){
    this.name = firstName;
    this.money = amount;
    this.status = function(){
        if(`${this.money} <= 1500000`){
            console.log(`${this.name} is poor`);
        }
       else{
            console.log(`${this.name} is rich`);
        }
    }
}
player1 = new persona('andy', 2000000);
player2 = new persona('sara', 1000000);
console.log(player1);

Error: Unable to resolve module @react-native-community/async-storage IOS

I am trying to run my react native project In my IOS device. I start my server with npx react-native start then I start my app with Xcode. And I get this error:

error: Error: Unable to resolve module @react-native-community/async-storage from /Users/nicolelopez/dev/LeksPlay/src/Core/onboarding/utils/AuthDeviceStorage.js: @react-native-community/async-storage could not be found within the project or in these directories:
  node_modules
  ../../node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
> 1 | import AsyncStorage from '@react-native-community/async-storage'
    |                           ^
  2 |
  3 | const SHOULD_SHOW_ONBOARDING_FLOW = 'SHOULD_SHOW_ONBOARDING_FLOW'

what I have tried:

  1. I have followed the commands I get In the error message:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
  1. i have deleted node_modules and my package.lock.json and have re-installed yarn and done a pod install.

  2. i have tried to restart the computer

  3. i have tried to do a yarn add @react-native-community/async-storage

  4. i am running on node 14 – because I have run in to similar issues with a higher version of node.

  5. i am running Xcode in Rosetta mode – since I am on a Mac M1.

  6. i have tried to change my AsyncStorage import to import AsyncStorage from '@react-native-async-storage/async-storage';

  7. I have also tried to add pod 'RNCAsyncStorage', :path => '../node_modules/@react-native-community/async-storage'

but they all result in the same issue – with is the error code I posted. It gets no different no matter what I try. I am really new to react native, this may be a common issue but I can’t seem to find anything that helps.

How to use put an ’empty’ value in react-hook-forms defaultValues with Typescript?

I use react-hook-forms with typescript and react native. When I set the defaultValues field in the useForm method I need to have in the beginning empty fields, there is no problem when the field is a string, but I have fields that for example should be a date. When I set the date to undefined I get a warning – fieldname is missing in the 'defaultValue' prop of either its controller or useForm, and when I try to set it to null I get some TypeScript error that the field in defaultValues must be either a Date or undefined, since react-hook-forms DefaultValues type can accept each field as an actual value or undefined.

So basically for each solution I get an error / warning. How can I solve that?

Thanks ahead.

Uncaught Type Error: Cannot read property ‘indexOf’ of undefined [closed]

I am working on a sign-in page in html, 🙂
And before you ask, this isn’t a duplicate.

Here is the html code:

<body>
<div class="sign">
<p>Username:</p>
<div class="incorrect incorrect-a" id="incorrect-a"><font size="2.3584782562126348594">Username must be a minimum length of 7 characters</font></div>
<input placeholder="Username" id="inc-a"></input>
<p>Email:</p>
<div class="incorrect incorrect-b" id="incb"><font size="2.3584782562126348594">Invalid Email</font></div>
<input placeholder="Email"></input>
<p>Password:</p>
<div class="incorrect incorrect-c"><font size="2.3584782562126348594">This password is not of good quality.</font></div>
<input placeholder="Password"></input>
<button class="submit" onclick="submit()"><span>Submit</span></button>
</div>
<script src="./signup.js" defer></script>
</body>

and js:

function submit(){
    const a = document.getElementById("inc-a").value;
    const b = document.getElementById("incb").value;
    console.log(a);
    var at = a.length;
    if(at<=7){
        console.log(2);
        const inca = document.getElementById("incorrect-a");
        inca.classList.add("show");
        setTimeout(()=> inca.classList.remove("show"), 5000)
    }
    if (b.indexOf('@') > -1) {
    console.log('has @');
}
}

But it flags up the following error:
Uncaught TypeError: Cannot read property ‘indexOf’ of undefined

Please help!