JS – Map/Array choice when both can do the same task

This is probably more of an opinion based question. But recently on a project I have seen that Map is always used over array.

My question is when would you ever use an array over a Map?

Note I mean in cases where an array would work as well as a Map.

i.e. storing data, checking it exists, and deleting it.

example here:

// Array
const teams = [];

if (teams.includes(team.id)) {
  return;
}

teams.push(team.id);

// do stuff

teams = teams.filter(
  (id) => id !== team.id
);


// Map
const teams = new Map();

if (teams.has(team.id)) {
  return;
}

teams.set(team.id, team.id);
// do stuff

teams(team.id);

As I understand Map is more performant, you also get methods like get, set, delete which are useful.

If faced with the task above what would people use and why?

Using JavaScript Variable in Thymeleaf

Lets say for example I have a variable b and c in:

<script th:inline="javascript">
let c = 20;
let b = 30;
document.getElementById("b").innerHTML = b;
        document.getElementById("c").innerHTML = c;
</script>

When I try to print them out on my page with :

 <h1>"The value for b is: " <span id="b"></span></h1>
<h1>"The value for c is: " <span id="c"></span></h1>

This works and the values of these varaibles are shown on the page.
Now that I’m using Thymeleaf and SPring I have a Controller methode like this:

     @GetMapping("/test")
        public String test( double val,  double val2,
                                     @RequestParam double rand, Model model) {
            model.addAttribute("val", val);
            model.addAttribute("val2", val2);
            model.addAttribute("rand", rand);
            model.addAttribute("distance", distance);
     
System.out.println(val);
        System.out.println(val2);
            return "/Test";
        }

I want to input only the rand, val and val2 should have the values from the JavaScript variables(b and c):

<form th:action="@{/test}"  method="get"><br>

    <input type="text" id="b" th:name="val" " th:value="${b}">
    <input type="text" id="c" th:name="val2" " th:value="${c}">



    <label for="rand">rand:</label>
    <input type="number" id="rand" th:name="rand" placeholder="rand" th:default="0"><br>




    <input type="submit" value="Submit" onclick="add()">
    <input type="reset" value="Reset">

</form>

But I am not getting the correct values from the JavaScript code.So I want to assign the variables b and c to the variables val and val2 so that I only need to input the request parameter rand.
Has anyone a solution for this.I looked it up and all the cases were that they wanted to assign the Thymeleaf variable in the script and not the other way around.
Thanks in advance

Trying to filter an object in javascript using lodash

I have some data like this, it’s more complex than this but this is the basic structure.

    {
        "AUDI": {
            "Id": "3",
            "Name": "AUDI",
            "Models": {
            "A1": [
                {
                "Model": "A1",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                },
                {
                "Model": "A1",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                }
            ],
            "A3": [
                {
                "Model": "A3",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                }
            ]
            }
        },
        "BMW": {
            "Id": "6",
            "Name": "BMW",
            "Models": {
            "1 SERIES": [
                {
                "Model": "1 SERIES",
                "TransmissionName": "Manual",
                "FuelTypeName": "Diesel"
                },
                {
                "Model": "1 SERIES",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                }
            ]
            }
        }
    }

I’m trying to filter the object down using a number of possible variables.

This is the code I’ve got so far:

    const newObj = _
    .chain(o).pickBy((o) => {
        if (makeId != null) {
            return o.Id == makeId // Corresponding to the Id value
        } else {
            return o
        }

    }).forEach((o) => {
        if (model != null) {
            return o.Models.Model == model // Corresponding to the Model value within the Models array
        } else {
            return o
        }

    }).value()

The first bit works (IE the Make selection), and I know I’m doing something fundamentally wrong on the .forEach part, but it just keeps returning the whole of the Make object, IE all the AUDIs or all the BWMs.

I would like to then be able to go on and filter by Model EG. is it petrol, is it a manual etc.

Would really appreciate some pointers please. Been trying to get this to work all day.

Thanks.

How to generate barcode inside mustache template – React/JS

Need to find a way to display a generated barcode inside a mustache template. Currently working with https://github.com/lindell/JsBarcode to generate the barcodes.

The syntax used for JsBarcode has me a bit confused as to how to pass the completed SVG code into the mustache template.

Using JSBarcode I render this barcode: barcode

via JsBarcode using:

 const data = '1234';

    JsBarcode('#barcode', data, {
      format: 'pharmacode',
      lineColor: '#0aa',
      width: 4,
      height: 40,
      displayValue: false,
    });

Which is rendered from the following HTML in the DOM:

<svg id="barcode" width="172px" height="60px" x="0px" y="0px" viewBox="0 0 172 60" xmlns="http://www.w3.org/2000/svg" version="1.1" style="transform: translate(0px, 0px);"><rect x="0" y="0" width="172" height="60" style="fill: rgb(255, 255, 255);"></rect><g transform="translate(10, 10)" style="fill: rgb(0, 170, 170);"><rect x="0" y="0" width="4" height="40"></rect><rect x="12" y="0" width="4" height="40"></rect><rect x="24" y="0" width="12" height="40"></rect><rect x="44" y="0" width="12" height="40"></rect><rect x="64" y="0" width="4" height="40"></rect><rect x="76" y="0" width="12" height="40"></rect><rect x="96" y="0" width="4" height="40"></rect><rect x="108" y="0" width="4" height="40"></rect><rect x="120" y="0" width="12" height="40"></rect><rect x="140" y="0" width="12" height="40"></rect></g></svg>

But in my code, the svg is just

<svg id="barcode" />

How can I pull this rendered svg’s HTML without going into the browser console and copy/paste?

To summarize, I’m looking for a way to generate this completed HTML and contain it within a variable inside my component to then pass to a mustache template.

How to plus input numbers in HTML with JS

i have the follow code:

<input type="number" name="pree" value="" id="pree" class="form-control">
<input type="number" name="pree1" value="" id="pree1" class="form-control">
<input type="number" name="pree2" value="" id="pree2" class="form-control">
<input type="number" name="pree3" value="" id="pree3" class="form-control">
<input type="number" name="result" value="" id="result" class="result">

I want to do a plus with all inputs, and im new in this process, but i try:

In JS:

<script>

    var num1= document.getElementByID('pree');
    var num2= document.getElementByID('pree1');
    var num3= document.getElementByID('pree2');
    var num4= document.getElementByID('pree3');
    
    var result=document.getElementByID('num1 + num2+ num3+ num4');

</script>

‘m really new to this and would like someone to help me with it, thank you very much in advance

Modify Class Method Definition in TS or JS

I have a class having structure like :

class A {
    constructor() {}
    myMethod() {
      console.log('in my method');
    }
}

I want to make a method that will accept className and methodName like :

modifyClassMethod(className, methodName)

This method should wrap the whole body of methodName specified into a callback during runtime.

So if I do,

modifyClassMethod(A, myMethod)

Now during runtime the body of myMethod of class A should get changed to

myMethod() {
   nr.recordMe('here', {
      console.log('in my method').
   })
} 

Now when I will create a new object of A class, then I will get modified value of myMethod.

How can I achieve this in TS or JS ?.

VS Code & Node.js: Use console() instead of consol.log()?

I’m writing JavaScript expressions to be used in specialized geospatial software.

In the geospatial software, only console() is valid, not console.log().


As I’m working, I’m debugging my geospatial scripts in VS Code using Node.JS (since the geospatial software doesn’t have linting functionality, etc.).

It’s my understanding that Node.js uses console.log() syntax, not console().

Therefore, when moving the script back and forth between the two programs, I need to do a find and replace to switch from console.log() to console(). This is becoming tedius.


Question:

In VS Code / Node.js, is there a way to use console() instead of console.log()? That would make things a lot easier when developing my scripts. Unfortunately, I can’t control things on the geospatial software side.

I’m a novice, so layman’s terms would be appreciated.

React Route for NAVLINK Received TRUE for a non-boolean attribute

I am using Navlink

import { NavLink } from "react-router-dom";
const MainMenu = () => {
    return (
        <nav className="main-menu d-none d-lg-block">
            <ul className="d-flex">
                <li>
                    <NavLink exact to="/">
                        Home
                    </NavLink>
                </li>
            </ul>
</nav>)};

I am getting a warning in my console saying

bundle.js:30762 Warning: Received `true` for a non-boolean attribute `exact`.
If you want to write it to the DOM, pass a string instead: exact="true" or exact={value.toString()}.
at a
at LinkWithRef (http://localhost:3000/static/js/bundle.js:59806:5)
at NavLinkWithRef (http://localhost:3000/static/js/bundle.js:59852:21)
at li
at div
at header
at Header (http://localhost:3000/static/js/bundle.js:11996:91)
at Routes (http://localhost:3000/static/js/bundle.js:60295:5)
at NavScrollTop (http://localhost:3000/static/js/bundle.js:3960:51)
at Wrapper (http://localhost:3000/static/js/bundle.js:4034:78)
at Router (http://localhost:3000/static/js/bundle.js:60228:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:59704:5)
at App

Any idea how can I fix it ? I tried other stack overflow details but could not come up with anything !! Thanks in Advance

Hide payment methods based select option?

Hi i want to show show payments methods based on country option selected.
i have following code.

FOR COUNTRY SELECTION

          $countries = json_decode(file_get_contents(resource_path('views/partials/country.json')));
   


<select name="country" id="countriess" class="form-control">
                         
                 <option value="nil"> -- select an option -- </option>
                        @foreach($countries as $key => $country)
                      
                            <option data-mobile_code="{{ $country->dial_code }}" value="{{ $country->country }}" data-code="{{ $key }}">{{ __($country->country) }}</option>
                         
                        @endforeach
                    </select>

To LOAD GATEWAYS

@foreach($gatewayCurrency as $data) // $data->country has country name from database

@endforeach

I have tried following using jquery

<script type="text/javascript">
           
   $('#countriess').on('change',function(){
     if("{{$data->country}}"!=$(this).val()){
            
      $("#country_{{$data->country}}").hide();
      
        }
       else if("{{$data->country}}"== $(this).val()){
           
        $("#country_{{$data->country}}").show();
        
        }
else if("{{$data->country}}"!=$(this).val()){
            
      $("#country_{{$data->country}}").hide();
      
        }
    });

        
        </script>

but issue is shows some other countries gateways as well if they are 2nd last in database

How to control microphone output from JavaScript?

I am building an app, which needs to record a microphone. I want users to control microphone output from the app, mute/unmute it.

Is it possible ? If yes, how can I achieve that ?

React version of the project

   "react": "^17.0.2",

Code where I get an microphono input

const handleRecord = async () => {
    setIsAudioLoading(true);
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/wav" });
    let orderNumber = 0;
    let chunks = [];

    mediaRecorder.ondataavailable = function (e) {
      chunks.push(e.data);
    };
    mediaRecorder.onstop = function () {
      const blob = new Blob(chunks, { type: "audio/wav" });
      streamChunk(blob, orderNumber, "mic");
      chunks = [];
    };

    mediaRecorder.start();

    setStopMic(() => () => {
      setIsMicPaused(true);
      setCurrentAudioTime(lastChunkSecondRef.current - 1.5);
      isMicPausedRef.current = true;
      mediaRecorder.stop();
    });
    setStartMic(() => () => {
      setIsMicPaused(false);
      isMicPausedRef.current = false;
      mediaRecorder.start();
    });

    setInterval(function () {
      if (!isMicPausedRef.current) {
        orderNumber++;
        mediaRecorder.stop();
        mediaRecorder.start();
      }
    }, MIC_INTERVAL);
  };

How can I use page.type() inside The page.$eval() in puppeteer?

    const browser = await puppeteerExtra.launch({
      "dumpio": true, // to log
      "headless": false, // to open browser in background process
      "devtools": false, // do disable dev-tools
      "ignoreHTTPSErrors": true, // to ignore webpage https error
      "args": [
        "--disable-setuid-sandbox",
        '--no-sandbox',
        '--disable-features=IsolateOrigins,site-per-process',
      ],
    });
    let page = await browser.newPage();
    await page.setUserAgent(userAgent.toString());
    await page.goto(url, { waitUntil: 'networkidle2' });
    await page.waitForTimeout(1000);
    await page.setCacheEnabled(false);
    await page.evaluate(() => {
      let modelSONATA = document.querySelector('input[id="model-SONATA"]');
      modelSONATA.click();
    });

i Want to Use page.evaluate() inside page.type so Please Help Me What is Way to Use Inside page.type()

clearInterval when you choose GOOD or WRONG answer JavaScript

Please help, I don’t know how to clear Interval when i choose good or wrong answer. Without choosing answer Interval clear when time goes to 0. When you choose a good option or a bad one, it moves to the next artboard, but the old interval still remains in the computer’s memory. I am not a coding specialist, which can be seen from my coding method… Game made in Adobe Animate.

createjs.Touch.enable(stage);
stage.enableMouseOver();

this.stop();
console.log("enter game")

let selected = [];
let finalMove = null;
let numberOfSec = 20;
//let level = 1;
//let score = 0;
this.timer.text = numberOfSec;
this.score.text = counterWin;

this.timer.visible = true;
this.timeplace.visible = false;

const timerInterval = setInterval(() => {
        numberOfSec--
    this.timer.text = numberOfSec;
    if(numberOfSec==5){
        this.timer.visible = true;
        this.timeplace.visible = true;
        createjs.Sound.play('clock');
        console.log("clock 5 to 0")
    }
    if(numberOfSec==0){
        this.gotoAndStop('next1')
        clearInterval(numberOfSec);
        console.log(numberOfSec);
        console.log("enter to page next1")
        createjs.Sound.stop();
    }
},1000)


const elements1 = [
this.mc1,
this.mc2,
this.mc3,
this.mc4,
this.mc5,
]


const places = [
    this.card1, 
    this.card2, 
    this.card3, 
    this.card4,
    this.card5,
];
    

shuffle(places);

elements1.forEach((element, index) => {
    element.x = places[index].x;
    element.y = places[index].y;
})


function shuffle(a) {
    let j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}


//var clear = clearInterval(numberOfSec);
var root = this;

elements1.forEach(element => {
    element.addEventListener('click', (event) =>{
    
        if (event.currentTarget.name === 'mc5'){
            console.log("GOOD")
            counterWin+=2;
            //clearInterval(numberOfSec);
            //root.clear;
            console.log(clear);
            this.score.text = counterWin;
            //createjs.Sound.stop();
            createjs.Sound.play('good');
            this.play();
            createjs.Sound.stop();
            console.log(counterWin);
        }else{
            console.log("WRONG")
            createjs.Sound.play('wrong');
            //clearInterval(numberOfSec);
            //root.clear;
            createjs.Sound.stop();
            this.play();
        }
        
        
    });
    
});

How can I replace a call argument of a function with Sinon?

I am using sinon to make my tests, and I faced a problem that I can’t find a proper solution

lets say, for simplicity, that I want, when I call console.log(),that the proper console.log receives the argument that I want in my test.

I have tryied:

Sinon.replace( console, 'log', () => console.log('mytestparam'))

Sinon.stub( console, 'log').callsFake( console.log('mytestparam'))

But it creates some kind of circular dependency that crashes

I cant simply make a full stub of the function, because it contains code that I want to run, I only want to replace the argument used for the call.

I have researched the sinon docs but I can’t find any function that allows to call the original function changing the args

Any idea?

How to get posts from the next pagination page using ajax?

There is a category on wordpress where posts and standard pagination 1, 2, 3, etc. are displayed. I made that when I clicked on the pagination, an Ajax request was triggered and from the next page of the pagination the posts were inserted into the page, but for some reason all the posts are displayed. Where am I wrong?

Post output code with pagination

<?php
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
    'cat' => $current_cat_id,
    'posts_per_page' => 1,
    'paged'          => $paged,
);

$query = new WP_Query( $args );
// Цикл
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
    $query->the_post();

?>

<a class="post-list-item mb-32" href="<?php the_permalink(); ?>">
    <div class="post">
        <div class="post-header mb-32">
            <div class="post-date">Jan 4, 2022</div>
            <h3 class="post-title"><?php the_title() ?></h3>
            <div class="post-short-info">
                <?php the_field('kratkoe_opisanie'); ?></div>
        </div>
        <div class="post-thumbnail">
            <div class="image-inner"><img class="image"
                    src="<?php echo get_the_post_thumbnail_url(); ?>">
            </div>
        </div><span class="read-more">Read more</span>
    </div>
</a>



<?php
}
} else {
    // Постов не найдено
}
// Возвращаем оригинальные данные поста. Сбрасываем $post.
wp_reset_postdata();

$big = 999999999; // уникальное число

$pagination =  paginate_links( array(
    'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'current' => max( 1, get_query_var('paged') ),
    'total'   => $query->max_num_pages
) );


?>

</div>

<?php
echo "<div class='pagination'>" . $pagination . "</div>";

?>

Ajax javascript

<script type="text/javascript">

        $('.pagination a').click(function(e) {

            e.preventDefault(); // don't trigger page reload

            if($(this).hasClass('active')) {
                return; // don't do anything if click on current page
            }

            $.post(
                '<?php echo admin_url('admin-ajax.php'); ?>', // get admin-ajax.php url
                {
                    action: 'ajax_pagination',
                    page: parseInt($(this).attr('data-page')), // get page number for "data-page" attribute
                    posts_per_page: <?php echo get_option('posts_per_page'); ?>
                },
                function(data) {
                    $('.posts-list').html(data); // replace posts with new one
                    console.log(data);
                }
            );
        });
</script>

Functions.php

function my_ajax_navigation() {
    $requested_page = intval($_POST['page']);
    $posts_per_page = intval($_POST['posts_per_page']) - 1;
    $posts = get_posts(array(
        'cat' => 6,
        'posts_per_page' => $posts_per_page,
        'offset' => $page * $posts_per_page
    ));
    foreach ($posts as $post) {
        setup_postdata( $post );
        echo $post->ID;
    }
    exit;
}
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );