Calculating the index to insert into a sorted array

I want to insert new elements not at the end of the array, but directly into a suitable position.
To do this, I use the .splice() method, in which I pass the callback function getSortPos()

acc.splice(getSortPos(acc, newAccount, compareAccounts), 0, newAccount)

This function takes an array, a new element and a compare function and calculates the appropriate position for inserting the new element

const getSortPos = (arr, el, cmpFn) => {
  let pos = 0;

  if (!arr?.length) {
    return pos;
  }

  while (cmpFn(arr[pos], el) < 0) {
    pos++;
  }

  return ++pos;
}

The solution seems to work at first glance but I think it has some flaws and does not look elegant.

I would be extremely grateful for any tips

Change button caption by condition React jsx

There is a button on the notes page with a deactivation function,
there is a note object (todo) it has an is_active property with a value of False or True , this property changes when clicked
please tell me how to make it so that when the button is pressed, the inscription changes along with the value: “Open” : “Closed”, how and where to write the condition correctly. I found an option, but for some reason it does not work. Here is my note code:

“””
const TodoItem = ({todo, deleteTODO}) => {
// if todo.is_active === ‘True’ ? button:’Open’ : button:’Closed’
return (

{todo.id}
{todo.name_project}
{todo.text}
{todo.date_create}
{todo.date_update}
{todo.creator}
{/{todo.is_active}/}

{todo.is_active === ‘True’ ?
<button onClick={() => deleteTODO(todo.id)} type=’button’>Open :
<button onClick={() => deleteTODO(todo.id)} type=’button’>Closed }

)
}
“””

JavaScript Menu Button

I have an issue with my Menu button in JavaScript.

When I click on the menu button it is supposed to switch to the main page but it won’t. Basically, my opacity should be 0 to 1 and the page should show up but I don’t know where I done wrong.

var btnMenu = document.getElementById("btn-menu");
btnMenu.addEventListener("click", toggleMenu);

function toggleMenu(e) {

var divOverlay = document.getElementByClassName("overlay")[0];
var speed = 10;

var eventTarget = e.target;

if(eventTarget.className == "btn-open"){
    fadeIn(divOverlay, speed);
    eventTarget.className = "btn-close";
    
} else if (eventTarget.className == "btn-close") {
    fadeOut(divOverlay, speed);
    eventTarget.className = "btn-open" 
}

}

function fadeIn(elem, speed) {
var inInterval = setInterval(function(){
    elem.style.opacity = Number(elem.style.opacity) + 0.02;
    if (elem.style.opacity >= 1) {
        
        elem.style.opacity = 1;
        clearInterval(inInterval);
    }
}, speed); // 10ms == .01s

}

function fadeOut(elem, speed) {
var outInterval = setInterval(function(){
    elem.style.opacity = Number(elem.style.opacity) - 0.02;
    if (elem.style.opacity <= 0) {
        
        elem.style.opacity = 0;
        clearInterval(outInterval);
    }
}, speed); // 10ms == .01s

}

Observable HttpEvent is not assignable to type Observable in Typescript

I’m calling REST API from my angular app, I’ve written below service class in typescript. I want to call different url and pass different headers based on the environment selection.
For example: if environment is dev then userURL value should be http://mydomain-dev.com/users/ and header should be devHttpOptions, similarly for QA – the userURL should be http://mydomain-qa.com/users/ and header should be qaHttpOptions and so on.

I’ve written below switch case statement, based on environment value, I’m deciding which url and header should be assigned.

But I’m getting below compile time error when I pass this.httpOptions in get method – this.http.get<User[]>(this.userURL, this.httpOptions)

Type 'Observable<HttpEvent<User[]>>' is not assignable to type 'Observable<User[]>'.
  Type 'HttpEvent<User[]>' is not assignable to type 'User[]'.
    Type 'HttpSentEvent' is missing the following properties from type 'User[]': length, pop, push, concat, and 28 more.ts(

Please find my code below:

UserService.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { User } from "./user";
import { HttpHeaders } from '@angular/common/http';


@Injectable({ providedIn: 'root' })
export class UserService {

    constructor(private http: HttpClient) { }

    userURL: any;
    httpOptions: any;
    devHttpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + btoa('dev-xxxx:yyyy')
        })
    };

    qaHttpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + btoa('qa-xxxx:yyyy')
        })
    };

    prodHttpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + btoa('prod-xxxx:yyyy')
        })
    };


    getUsers(environment): Observable<User[]> {

        console.log(environment);
        switch (environment) {
            case 'dev':
                this.userURL = 'http://mydomain-dev.com/users/';
                this.httpOptions = this.devHttpOptions;
                break;
            case 'qa':
                this.userURL = 'http://mydomain-qa.com/users/';
                this.httpOptions = this.qaHttpOptions;
                break;
            case 'prod':
                this.userURL = 'http://mydomain-prod.com/users/';
                this.httpOptions = this.prodHttpOptions;
                break;

        }
        return this.http.get<User[]>(this.userURL, this.httpOptions);
    }

}

Could you please help me with this issue. Appreciated your help in advance!
Thanks!

I need help understanding a Javascript function used to search a list with a search bar so I can modify it to search a table

I’m working on a college assignment where I use a PHP class to generate table values which a Javascript function then searches with a search bar. It builds off of a previous assignment that uses the same search bar to search an unordered list. It worked great for the list but it uses a function that was already supplied to me which, frankly, I don’t know how it works. Now all it does, once I add a table row with more than one cell, is search the first cell. It still returns the whole row but I also need it to search the whole row.

It seems like a = tr[i].getElementsByTagName("a")[0]; only returns the first <a> and this might be the problem, but I don’t know how to go about fixing that in a was that doesn’t break the function.

The function that’s confusing me follows. I added my own code to it to hide the list/table which obviously I understand. I won’t include that but that’s why you don’t see me close the function, just so you’re not confused about that.

function myFunction() {
    var input, filter, table, tr, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase(); 
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
            
    for (i = 0; i < tr.length; i++) {
        a = tr[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
        } else {
            tr[i].style.display = "none";
        }
    }

For reference, here is the multi-cell table row I added for testing, which is now giving me problems. I also include the actual search bar itself because it contains relevant syntax for explaining the functionality. There are other rows so the table closes later on.

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">     <!--This is my search bar-->
<table id="myTable" onload="hideList()">
    <tbody>
        <tr id="1">
            <?php 
                $pr0 = new productRow(0);
                echo 
                    "<td><a href="#">" . $pr0->itemNumber . "</td></a>" . 
                    "<td><a href="#">" . $pr0->name . "</td></a>" . 
                    "<td><a href="#">" . $pr0->type . "</td></a>" .               //These rows concatenate the class instances with the elements in which they are supposed to appear
                    "<td><a href="#">" . $pr0->model . "</td></a>" . 
                    "<td><a href="#">" . $pr0->brand . "</td></a>" . 
                    "<td><a href="#">" . $pr0->description . "</td></a>";
            ?>
        </tr>

And I’ll include the PHP class just so you can see how it inputs things, but don’t worry, it works.

<?php
    class productRow {
        var $itemNumber = [];
        var $name = [];
        var $type = [];
        var $model = [];
        var $brand = [];
        var $description = [];
        function __construct($i) {                                  //receives argument when class is called with an argument
            $this->itemNumber = $this->make_table_row($i)[0];
            $this->name = $this->make_table_row($i)[1];
            $this->type = $this->make_table_row($i)[2];
            $this->model = $this->make_table_row($i)[3];            //This function allows the instance values of the attributes to be taken from the make_table_row function
            $this->brand = $this->make_table_row($i)[4];
            $this->description = $this->make_table_row($i)[5];
        }
        function make_table_row($i) {                               //receives argument when class is called with an argument
            $row = 1;
            $tablerows = [];
            if (($input = fopen("input.csv", "r")) !== FALSE) {                 //gets the CSV with my table data
                while (($tabledata = fgetcsv($input, 1000, ",")) !== FALSE) {   //cycles through the rows of data creating arrays
                    if ($row == 1) {
                        $row++;     
                        continue;       //skips the first row because it's a header row I don't want on my input
                    }
                    $tablerows[] = $tabledata;      //uses the roles to populate a multidimensional array
                    $row++;
                }
                fclose($input);
                if (isset($tablerows[$i])) {
                    return $tablerows[$i];              //uses argument to return the appropriate array
                }
            }
        }
    }
?>

Can anyone shed some light on what is going on here and how I might get all of the <a> elements without breaking the function?

adding quantity through buttons to a shopping cart item – Javascript

I am working on a personal project, just practicing on my own and getting to know and familiarized with the language.I am trying to learn by doing so I am creating a shopping cart and I came across a situation that I can not find a proper solution.

I have a list on my shopping cart already rendered of n items. When I ‘click’ on a plus button to add quantity to an item, it only adds to the quantity to the item that is first on the list and the ‘price’ of the second item.

Thank you in advance!

   function renderCarrito(){  
   // carritoEl.innerHTML = "";
    while(carritoEl.firstChild){
        carritoEl.removeChild(carritoEl.firstChild)
    };

    carrito.forEach((item) =>{

        carritoEl.innerHTML += `
        <li class="buyItem">
            <img src=${item.image}>
            <div class="productCartInfo">
                <h5 class="prdTitle">${item.title}</h5>
                <h6>${item.price}</h6>
                <div class="qnty">
                    <div>
                        <button class="mbtn">-</button>
                        <span class="countOfProduct">${item.cantidad}</span>
                        <button class="pbtn">+</button>
                    </div>
                    <div><i class="fas fa-times-circle dltProduct" data-id="${item.id}"></i></div>
                </div>
            </div>
        </li> 
        `

        const plusBtn = document.querySelectorAll('.pbtn');
        const minusBtn = document.querySelectorAll('.mbtn');
        const count = document.querySelector('.countOfProduct');


        plusBtn.forEach(pbtn =>{
            

            pbtn.addEventListener('click', () => {


                item.cantidad++;

                count.innerHTML = item.cantidad;

                carritoSumaTotal();


        })});


    })


    carritoSumaTotal();
    
}

``

Vue 2 Reactivity: computed property doesn’t trigger DOM update

I have a computed property based on some nested object properties. When the object gets changed, the computed property seems to update (In vue-dev-tools) but the change is not reflected in the UI. I’m aware of nested object reactivity, but I never change/assign a nested property of my order object, the only time it changes is in the updateOrder() (which assigns the object at the root level.

Is there a reason why my UI isn’t updating? Are the dev tools synced to the sames state as the UI is? Am I missing something about Vue’s reactivity system?

Here is some very simplified code:


<template>
  <my-component
    @order-changed="updateOrder"
  />
  <div v-if="isOrderComplete">
    Your order is complete  // this never shows until I refresh page
  </div>
  <div v-else>
    Please Submit the order  // this shows at first
  </div>
</template>


export default {
  props: function(){
    initialOrder: Object,
  },
  data: function(){
    order: this.initialOrder
  },
  methods: {
    updateOrder: function(newOrder){  // gets triggered by a child component
      this.order = newOrder;
    }
  },
  computed: {
    isOrderComplete: function(){  // starts as false, becomes true later, seems to be updated in dev-tools
      return this.order.foo || this.order.bar
    }
  }
}

auth.currentUser shows undefined on HomePage

I have a file where I have written all the firebase related functions, including this one here

function CurrentUser(){ return auth.currentUser }

When I log auth.currentUser inside the function above, I can see details of currently logged in user but when I call this function on React homepage, I see it being undefined.
Also I could see the homepage logs as expected if I make any changes like adding let i=1 in the above function. Wasn’t able to figure out what’s going on here. Any help would be appreciated.

sinon.spy on “import * as Module” fails after updating to Webpack 5

I am working on upgrading an application from Webpack 4 to Webpack 5. It uses babel-loader. I have production code working, but am stuck on our Karma/Sinon integration tests after upgrading to karma-webpack v5.

This code worked previously, but now throws an error:

// useEditUI.ts
export default function useEditUI() {}

// integration.ts
import sinon from 'sinon';
import * as useEditUI from 'useEditUI';

const spy = sinon.spy(useEditUI, 'default');

enter image description here

My understanding is that this is occurring because of how import/export is managed under-the-hood:

enter image description here

Previously, the spy logic was looking at a configurable object with value set to the default export. Now, the object is not configurable, there is no value property, and, instead, there’s a getter which maps to the default function

enter image description here

This breaks sinon.spy functionality.

After researching the problem for a while I found a couple of potential libraries which could help:

None of these libraries seemed to “just work” and several of them appear abandoned. In general, they seem to force an expectation of using commonjs module syntax. All other research has resulted in posts announcing the solution as import * as Module which is how the original solution came to exist in the first place.

I do not have this issue when working with more modern testing tools, such as Jest. This is just a limitation with sinon that I am attempting to mitigate.

Does anyone have workable guidance here? Thanks


Advice on Filtering Availability Based on dates

I am trying to show availability for specific resorts over the course of a month. The resorts all have different rooms and different week end days based on the room. I need to be able to show valid check in days based on availability with respect to their week end days.

That probably does not make too much sense so let me elaborate. Let’s assume person A wants to book a room for 3 days. In order for a check in day to be valid the room has to have continuous availability (I.E. Available 05/03, 05/06, 05/07, and 05/08 -The check in day does not count towards the three day stay). In order for the check in day to be valid it also must respect the week end day. For example Let’s assume the person wants to book a 3 day stay in a one bedroom unit with a week end day of Saturday. Assuming continuous availability this would mean that valid check in days would be the following: (Saturday, Sunday, Monday, Tuesday, and Wendsday) and we would need to filter out availability on Thursday and Friday

This is where I am struggling a bit. The API endpoint that I am calling returns availability as datetime strings. I originally thought that I could just call the Date.getDay() function on the Date and then check if the week end date was greater than the day + duration of stay. However the getDay function returns 0 for Sunday, 1 for Monday, etc. so most numbers would be greater than these days. For instance if the week end day is a Sunday any number would be greater than 0 and therefore the room would show no availability.

Another option I thought of was to create a hashgraph with all the possible combination of days, but this would be a lot of work so I would like to avoid it if possible. I am hoping that there is an easy enough solution that I am not thinking of.

MathJax in Android WebView – injecting the script after the HTML page is loaded

I have to add MathJax functionality to my app.

According to some examples the correct script to be added is

<script type='text/x-mathjax-config'>"
                            +"MathJax.Hub.Config({ "
                           + "showMathMenu: false, "
                           + "jax: ['input/TeX','output/HTML-CSS'], "
                           + "showProcessingMessages: false, "
                           + "messageStyle: 'none', "
                           + "extensions: ['tex2jax.js'], "
                           + "TeX: { extensions: ['AMSmath.js','AMSsymbols.js',"
                           + "'noErrors.js','noUndefined.js'] } "
                           + "});</script>"
                           + "<script type='text/javascript' "
                           + "src='file:///android_asset/MathJax/es5/tex-mml-svg.js'"
                           + "></script><span id='math'></span>

The script is loaded from local folder inside the Asset directory.

I have to add that script to a local HTML file when loaded in the Android WebView from another folder on the filesystem (private app folder).

The HTML page has math formulas inside that have to be read by the MathJax functions.

I cannot inject the script as a tag in the HTML file before loading. But also the rendering of the formulas have to be performed immediately after loading.

In the examples they suggest something like:

webView.loadDataWithBaseURL("http://bar", "<script type='text/x-mathjax-config'>"
                        +"MathJax.Hub.Config({ "
                       + "showMathMenu: false, "
                       + "jax: ['input/TeX','output/HTML-CSS'], "
                       + "showProcessingMessages: false, "
                       + "messageStyle: 'none', "
                       + "extensions: ['tex2jax.js'], "
                       + "TeX: { extensions: ['AMSmath.js','AMSsymbols.js',"
                       + "'noErrors.js','noUndefined.js'] } "
                       + "});</script>"
                       + "<script type='text/javascript' "
                       + "src='file:///android_asset/MathJax/es5/tex-mml-svg.js'"
                       + "></script><span id='math'></span>","text/html","utf-8","");    

That instruction is executed after the page is loaded, followed by

webView.evaluateJavascript("MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");

that I think is the instruction to render all the math tags in the document

but I get

I/chromium: [INFO:CONSOLE(1)] "Uncaught ReferenceError: MathJax is not defined"

What is the correct way to inject the script in the loaded page and perform the rendering?

How to use the same JS code (text with a checkbox with some css) to create hundreds of the same element automaticly

I’m so sorry if this is a very stupid question but I know this site helps newbie’s for a long time, and if you can help me on this issue it would be INCREDIBLY appreciated…

Alright where to start. I am learning JS / HTML / CSS and decided to put my “skills” into my first real test. Before, i’ve published some mildly-static-JS-flawored site’s, but now i am working on a site based on the National Anthem’s of the great countries of the Earth.

Anyway, i’ve finished the Greetings page and it came to making the song’s get listed and here is where my problem began. You see i managed create a div that i can play music when i press (here for the HTML, JS and CSS: https://jsfiddle.net/Tylanmon/by5Lcvw0/4/ And here’s just JS:

var Song_Name = document.createTextNode('La Marseillaise')

var div = document.createElement('div')
div.setAttribute('class', 'div')
var checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.name = 'checkNAME'
checkbox.id = 'checkID'

var label = document.createElement('label')
label.id = 'nameID'
label.htmlFor = 'checkID'
label.appendChild(Song_Name)

div.appendChild(label)
div.appendChild(checkbox)

document.getElementById('songs').appendChild(div)
//  
var length = label.offsetWidth  
var length2 = checkbox.offsetWidth
console.log(length);

div.style.width = `${length + (length2 * 2 - 5.9)}px`;
div.style.backgroundColor = 'whitte'
div.style.borderRadius = '4px'
div.style.border = `1px solid black`;

but the problem is that there are hundreds of anthems that i want to include, and i dont wanna manually copy and paste and change the div of the new songs and so an and so fort!

Now, i know that to change that I need to writte back-end magical codes but as i said, I know nothing about backend, and though i’d LOVE to learn, it just have to wait for another day…

TLDR: I need hundreds of the same elements with different ID’s so they can trigger different songs, without actually changing their ID manually.

If you think this is a stupid question, yes it definetly is- but i sincerely ask you to not downvote so some other person mayy see and want to help. Thank you.

Javascript functions stop working when using import at top of script, even without trying to use what’s imported

I’m trying to recreate a simple program of mine using lit instead of just basic js, but adding import statements seems to break every function.

Things seem to work just fine with "type": "module" alone in my package.json, but the second I change type="text/javascript" to type="module" in my script link within my html, or when I add:

import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';

to the top of my app.js, or even both in combination, none of my functions seem to work anymore.

I tried changing the scope of my functions as suggested in this thread: Functions not working when “`type=”module”“` or import , but that didn’t seem to have any effect.

Here is an example of one such function:

function initialize()
{
    xWins = window.sessionStorage.getItem('xWins');
    oWins = window.sessionStorage.getItem('oWins');
    draws = window.sessionStorage.getItem('draws');
    if(xWins == null) { xWins = 0; }
    if(oWins == null) { oWins = 0; }
    if(draws == null) { draws = 0; }
    document.getElementById('numXWins').innerHTML = "X WINS: " +xWins;
    document.getElementById('numOWins').innerHTML = "O WINS: " +oWins;
    document.getElementById('numDraws').innerHTML = "DRAWS: " +draws;
}

Is there something I’m missing? How can I keep my functions working after I add import statements?