Need Help JavaScript Challenge

I can’t seem to pass the test for this challenge.

// Write a function that takes 6 values (a,b,c,d,e,f) as arguments
// Sum a and b
// Then substract by c
// Then multiply by d and divide by e
// Finally raise to the power of f and return the result
// Tipp: mind the order

function myFunction(a, b, c, d, e, f) {

    return 
}

Script dynamically inserted later on: how to make it run?

In my React app, I have scripts that are inserted dynamically later on. The scripts don’t load.

A field called content in my database for example contains data such as the following:

<p>Some text and html</p>
<div id="xxx_hype_container" style="width: 46px; height: 50px; overflow: hidden;">
<script type="text/javascript" charset="utf-8" src="https://example.com/uploads/hype_generated_script.js?499892"></script>
</div>
<div style="display: none;" aria-hidden="true"> 
<div>Some text.</div> 
Etc…

In my React app, I call on this db field to display that content:

import { thePost } from "../../../appRedux/actions/postAction";

class Post extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            post: "",
        };
    }

    componentDidMount() {
        // get post data from db
        this.props.thePost(this.props.match.params.postId);
    }

    render() {
        return (
            <div className="container">
                {post.content}
            </div>
        )
    }
}

It correctly loads the data from the database and displays the html from that data. But the data also contains a script, which does NOT get loaded. I think the script doesn’t work because it is dynamically inserted later on. How can I make this script work/run?

This post suggest a solution for dynamically inserted scripts, but I don’t think I can apply this solution because in my case the script/code is loaded from a database (so how to then use nodeScriptReplace on the code…?). Any suggestions how I might make my scripts work?

Symfony live search bar with ajax

I’m very new with ajax, I have a page which displays all formations on my Symfony online learning website, and I’m trying to make a search bar which would display the results without refreshing the page. If you don’t type anything, all formations show, if you type something you get matching results or an error message, without refreshing the page by using a submit button.

I’ve already looked into Ajax requests, I’m not sure I understand everything. I understand I need to get the string the user types in the bar by using onkey and getting the input and then make a query that selects formations in the database which titles match the input, and process it through the controller.

Here’s my twig view on which all formations are displayed:

{% extends 'base.html.twig' %}
{% block title %}Formations{% endblock %}
{% block content %}
    <div class="blockcontainer text-center">
        <h1>Nos formations</h1>
        <br>
            <input type="text" class="form-control" id="live_search" placeholder="Rechercher une formation">
        <br>
        <div class="row justify-content-md-center" id="search_results">
                {% for formation in formations %}
                    <div class="col-xl-2">
                        <div class="card">
                            <img class="card-img-top" src="{{ vich_uploader_asset(formation, 'imageFile') }}" alt="{{ formation.imageName }}">
                            <div class="card-body">
                                <h5 class="card-title">{{ formation.title }}</h5>
                                <p class="card-text">{{ formation.description }}</p>
                                <a class="small btn btn-success custom-btn rounded-pill px-3" href="{{path('app_formations_see', {'id' : formation.id })}}" role="button">voir</a>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            </div>
    </div>
{% endblock %}

I also read you shouldn’t display results in a view that extends a template?
How do I go around this? thanks!

Does Google Apps Script (GAS) support proper tail calls or tail call optimization?

I’m wondering whether investing time into doing tail call optimization for a Google Apps Script is worth it.

So, I’ve understood that Google Apps Script uses the ES2015 (ES6) version of the JavaScript specification (ref1, ref2), running it on the V8 runtime implementation.

Supposedly, ES2015 supports (proper) tail call optimization from the spec. But there are some indications that V8 actually doesn’t implement it:

Furthermore, I’ve learned there is an important nuance here:

The terminology of proper tail calls (PTC) and tail call optimization (TCO) is often conflated. Here’s the difference between the two:

  • proper tail calls: functions called in the tail position reuse the current stack frame, preventing the creation of additional stack frames that cause space inefficiency.
  • tail call optimization: rewrites a recursive function into an iterative one, usually by calling goto.

PTC only deals with stack manipulation, while TCO rewrites a recursive
function as an iterative function.

So, given this…

Does Google Apps Script (GAS):

  • support proper tail calls? My guess from the above is “No.”, but it’d be nice to have an authoritative answer, as far as possible.
  • support tail call optimization to the point where it is worth doing it, for performance, in any way? My guess is “Yes, you can do it, but it doesn’t improve performance.” But it’d be nice if someone knew it definitively, or could point to a GAS performance comparison that demonstrates it.

How to make when bot ask a question, he waiting for an answer and ask another question

I wanted to create my bot for economics, but I ran into a problem. What do I want to do: after writing one question, the bot waits for an answer and then asks another question and so on. Can someone help me with my problem? Currently I have something like this:

const config = require('../../config.json');
const { MessageEmbed } = require('discord.js');
const shopEconomy = require('../../database/shopEconomy');

module.exports = {
    name: 'create-item',
    aliases: [],
    description: '',
    run: async(client, message, args) => {
        const items = require('../../items.json');
        const item = items[Math.floor(Math.random() * items.length)];
        const filter = response => {
            return response.content.toLowerCase();
        };
        const embed = new MessageEmbed()
        .setColor(`${config.correct}`)
        .setAuthor({ name: `Item` })
        .addFields(
            { name: `Name`, value: `---`}
        )

        return message.channel.send(item.question, { fetchReply: true, embeds:  })
        .then(() => {
            message.channel.awaitMessages({ filter, max: 1, time: 10000, errors: ['time'] })
            .then(async collected => {
                const embed = new MessageEmbed()
                .setColor(`${config.correct}`)
                .setAuthor({ name: `Item` })
                .addFields(
                    { name: `Name`, value: `${collected.first()}`}
                )
        
                    await shopEconomy.findOneAndUpdate(
                        {
                            guildID: message.guild.id,
                        },
                        {
                            name: `${collected.first()}`,
                        },
                        {
                            upsert: true,
                        }
                    );

                return message.channel.send({ embeds:  });
            })
            .catch(collected => {
                const embed = new MessageEmbed()
                .setColor(`${config.false}`)
                .setDescription(`Timeout.`)

                message.channel.send({ embeds:  });
            });
            
        });
    }
}

Image Optimization, long list data fetched from Rest API and rendering the top of the home page on a new user’s first visit

Can someone help me to answer these questions? I did it but I would like to have an expert opinion on these field. Here we is the case:

Please provide options of what someone can do to improve the performance of a website for each of the following topics. Imagine that an engineering manager has given you the freedom to improve the following items on a website for the next month. What would you tell the manager you would take a look at? Bonus: Please add any details to your list, if time allows, to showcase your knowledge.

displaying images
displaying long lists of data fetched from a REST API
rendering the top of the home page on a new user’s first visit as soon as possible

A React component’s function is not recognized as a function when passed in as a parameter

I’m trying to pass a function as a parameter for a component, however it does not see the function I pass in as a function.

Here’s the page (I’m only going to provide what’s imoprtant)

const Home = () => {
const nav = useNavigate()

const [userList, setUserList] = useState([]);
const [loggedInUser, setLoggedInUser] = useState({});
const [currentChat, setCurrentChat] = useState(undefined);
const [showMenu, setShowMenu] = useState(false);

let navMenu    


const handleChatChange = (chat) => {
    setCurrentChat(chat);
}



return (

        <div id='sidebar'>
            <div>
                <Userlist users={userList} switchChat={handleChatChange}/>
            </div>
        </div>
)

Here is the react component that provides the error

const Userlist = ( props, switchChat  ) => {

const switchCurrentchat = (user) => {
    switchChat(user);
}

return (
        <div>
            <div id='home-header'>
                <h1>DevsHelp</h1>
            </div>

            <div id='userlist'>

                {props.users.map((user) => {
                    return (
                        <div key={user._id} className='user' onClick={() => switchCurrentchat(user)} >
                            <h3>{user.username}</h3>
                        </div>
                    )
                })}
            </div>
        </div>
)}

Whenever switchChat is called upon, it returns an error stating “switchChat” is not a function.

If I do a console.log(user) instead of switchChat(user), it logs the user, so the function works, however it’s just not reading it as a function.

If anyone could help me, I would appreciate it a lot, thanks!

Proper class format in modern ES

Is the following an acceptable way to initialize a class?

class Person {
    name = undefined; // or just `name` ?
    age = undefined; // or just `age` ?
    constructor(name, age) {
        Object.assign(this, {name, age});
    }
}
let p = new Person('tom', 10);

By that I mean, more specifically,

  • Is Object.assign(this, {...variables}) a good way to do all the this assignments?
  • Is it considered good practice to stick the variables at the top, or should they be placed within the constructor?
  • Is it better to explicitly set a variable to undefined or not? That is, is name = undefined; or name; preferable?

Typescript can’t find module of a referenced Project

I am trying to share code between 2 seperate Typescript projects.
To demonstrate this easily reproducable problem I created a minimal repository here (Including instructions to reproduce):
https://github.com/realdegrees/ts-function-reference/tree/master/project

You can check out the repo or the following code snippets.
The issue is that I can import e.g. interfaces and enums just fine and they work (ran the code and had the enums logged) but as soon as it’s a function I’m trying to import it doesn’t work anymore.

Running tsc works fine and throws no errors. You can even see that typescript resolves the module in question perfectly fine.

❯ tsc --traceResolution | grep 'reference/lib'
======== Resolving module '../reference/lib' from '/home/fasc/projects/reference- 
test/project/index.ts'. ========
Loading module as file / folder, candidate module location 
'/home/fasc/projects/reference-test/reference/lib', target file type 'TypeScript'.
File '/home/fasc/projects/reference-test/reference/lib.ts' exist - use it as a name 
resolution result.
======== Module name '../reference/lib' was successfully resolved to 
'/home/fasc/projects/reference-test/reference/lib.ts'. ========
======== Module name './lib' was successfully resolved to 
'/home/fasc/projects/reference-test/reference/lib.ts'. ========

However as soon as I try to start the project it’s the ‘ole
Error: Cannot find module '../reference/lib'

I have tried importing the index.ts, lib.ts directly and paths in tsconfig.ts.
References are setup correctly and it obviously works with types but for some reason not functions.

The project looks like this: [Image][1]

Files:

////////////// project/index.ts
// None of these work
import { foo as regularDirectImport } from '../reference/lib';
import { foo as regularIndexImport } from '../reference/index';
import {foo as pathsImport} from '@reference';
pathsImport();
regularDirectImport();
regularIndexImport();

/////////// project/tsconfig.ts
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "dist", 
    "esModuleInterop": true, 
    "forceConsistentCasingInFileNames": true, 
    "strict": true, 
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@reference": ["../reference/index"]
    }
  },
  "references": [
    {
      "path": "../reference"
    }
  ]
}

////////// reference/index.ts
export * from './lib';

////////// reference/lib.ts
export const foo = () => {
    console.log('bar');
}

////////// reference/tsconfig.ts
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": "src",
    "declaration": true,
    "declarationMap": true,
    "composite": true
  }
}

I would die for some help, I have found several guides on how to import code from external typescript projects and they all mention that functions work as well but I just cannot get it work.
[1]: https://i.stack.imgur.com/KXOGc.png

Scroll to the top of modal window on button click

I’m building a site on WordPress using Elementor page builder, and I’m having trouble sending the user back to the top of a modal when clicking ‘next’ on a form.

Here’s the code I’ve been trying, and here’s the page it’s currently hosted: http://doortouk-co-uk.stackstaging.com/home/

(The modal can be opened by clicking the ‘Apply Now’ button at the bottom of the page, section 3, 4 and 5 have the longer sections that require the scroll to top functionality)

jQuery(document).ready(function () {
    jQuery('.e-form__buttons__wrapper__button-next').click(function(){
        jQuery(".dialog-widget-content").scrollTop(0);
        });
 })

Any help would be appreciated!

how to prevent multiple copies of React when developing library with Rollup?

I am developing tiny ui react library. I am using Rollup as a bundler. and i faced some strange issue:

react.development.js:1476 Uncaught Error: Invalid hook call. Hooks can only be called 
inside of the body of a function component. This could happen for one of the 
following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Here is my Rollup config:

import babel from "rollup-plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import external from "rollup-plugin-peer-deps-external";
import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";
import typescript from "rollup-plugin-typescript2";
import peerDepsExternal from "rollup-plugin-peer-deps-external";

const packageJson = require("./package.json");

export default [
  {
    input: ["./src/index.ts"],
    output: [
      {
        file: packageJson.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    globals: {
      react: "React",
      "react-dom": "ReactDOM",
    },
    external: ["react", "react-dom"],
    plugins: [
      peerDepsExternal({ includeDependencies: false }),
      postcss({
        plugins: [],
        minimize: true,
      }),
      babel({
        exclude: "node_modules/**",
        presets: ["@babel/preset-react"],
      }),
      external(),
      resolve(),
      typescript({ useTsconfigDeclarationDir: true }),
      terser(),
    ],
  },
];

Component itself if very simple. Nothing special so i am skipping its code.
When i am publishing my lib to NPM – everything is working exactly as expected.

But when i am doing local instal with

npm i ../my-local-lib

I have this error in console:

react.development.js:1476 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

My expectation was that peerDepsExternal plugin will handle this case, but obviously i have messed up somewhere.

JS library for HTML formatting

Is there at least one good js library which can format an html code string?
I mean, i have a string variable with an html code in it. All i want is to call just one single function from the library to format this long ugly html line into the pretty html code and print it in the textarea.
I was searching on npmjs.com, but nothing was found, maybe i’ve missed something.

When using PHP to save a drop down menu selection it remembers the selection but doesnt trigger the onchange event changing the CSS when reloaded

So basically I need to have a PHP cookie I cannot use JavaScript to save the information even though I would like to do so. It saves the selection fine but when reloaded the selection doesnt trigger the onchange which im assuming is the problem. Due to this the CSS doesnt change and it loads into light mode even if dark mode is selected.

Here is my code (PHP/HTML):

<?php
$theme = null;
if (isset($_POST["setc"])) {
    $expire = time() + 60 * 60 * 24 * 30;
    setcookie("mycookie", $_POST["navyOp"], $expire);
    header("location: " . $_SERVER["PHP_SELF"]);
} else if (isset($_COOKIE["mycookie"])) {
    $theme = $_COOKIE["mycookie"];
}
?>
<div class="Button">
        <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
            <select name="navyOp" onchange="test(this);">
                <option selected="selected">Choose a Theme!</option>
                <option value="val1" <?php echo (!is_null($theme) && $theme === "val1" ? " selected" : ""); ?>>Light</option>
                <option value="val2" <?php echo (!is_null($theme) && $theme === "val2" ? " selected" : ""); ?>>Dark</option>
                <input name="setc" value="theme_setting" type="submit">
            </select>
        </form>
    </div>

The JavaScript:

window.test = function(e) {
  if (e.value === 'val1') {
    document.getElementById("container").style.cssText = "background-color: white;";
    document.getElementById("start").style.cssText = "border: 2px solid lightgrey; color: lightgrey; ";
    document.getElementById("choice").style.cssText = "border: 1px solid grey; ";
    document.getElementsByTagName("html").style.cssText = "background-color: white;";
      

  } else if (e.value === 'val2') {
    document.getElementById("container").style.cssText = "background-color: black;";
    document.getElementById("start").style.cssText = "border: 2px solid lightgrey; color: lightgrey; ";
    document.getElementById("choice").style.cssText = "border: 1px solid white;";
    document.getElementsByTagName("html").style.cssText = "background-color: black;";
  }
}

And CSS even though its not necessary:

#container{
    margin: 20px auto;
    background-color: white;
    height: 900px;
    width: 1850px;
    border-radius: 5px;
    box-shadow: 0px 5px 15px 0px;
    position: relative;
}

#start{
    font-size: 1.5em;
    font-weight: bolder;
    word-break: break-all;
    width:100px;
    height:150px;
    border: 2px solid lightgrey;
    text-align: center;
    cursor: pointer;
    position: absolute;
    left:875px;
    top:350px;
    color: grey;
}

html{
    background-color: white;
}

.choice{
    display: inline-block;
    width: 135px;
    text-align: center;
    border: 1px solid grey;
    border-radius: 5px;
    cursor: pointer;
    padding: 5px;
    color: grey;
}

Thank you for your time 🙂