javascript recursion not working as expected

I’m trying to write functionality something like this:

Input:

['A', '-B1', '--B2', '-C1', 'D']

Output:

{'A': {'B1': {'B2': {}}, 'C1': {}}, 'D': {}}

As you can see that B1 and C1 are children of A and B2 is a child of B1. It can go any level nested based on -

I wrote a Javascript code for the same but it seems something wrong when children are created. Here is my code:

function fetch_levels(li, chr='-') {
    var res_list = []
    for (i=0; i<li.length; i++) {
        item = li[i]
        level = item.length - item.replace(RegExp(`^${chr}+`), '').length
        key = item.replace(RegExp(`^${chr}+`), '')
        value = {}
        res_list.push({
            level: level,
            name: key,
            value: value
        })
    }
    return res_list
}

function ttree_to_json(ttree, level=0) {
    result = {}
    for (i = 0; i < ttree.length; i++) {
        cn = ttree[i]
        nn = ttree[i+1] || {'level': -1}

        // Edge cases
        if (cn['level'] > level) {
            continue
        }
        if (cn['level'] < level) {
            return result
        }

        // Recursion
        if (nn['level'] == level) {
            result[cn['name']] = cn['value']
        } else if (nn['level'] > level) {
            rr = ttree_to_json(ttree.slice(i+1), level=nn['level'])
            result[cn['name']] = rr
        }
        else {
            result[cn['name']] = cn['value']
            return result
        }
    }
    return result
}

And this is how the functions can be invoked:

console.log(ttree_to_json(fetch_levels(['A', '-B1', '--B2', '-C', 'D'])))

And the output I got is something like:

Object { B2: {…}, C: {} }

Which is wrong.

Note: Same logic is applied in the python program and it seems to be giving the correct output. I’m not able to figure out what is going wrong in JavaScript. For reference, I’m mentioning the working version of the Python program as well:

def fetch_levels(li: list, split_char='-'):
    res_list = []
    for item in li:
        level = len(item) - len(item.lstrip(split_char))
        key = item.lstrip(split_char)
        val = {}
        res_list.append({'level': level, 'name': key, 'value': val})
    return res_list


def ttree_to_json(ttree, level=0):
    result = {}
    for i in range(0, len(ttree)):
        cn = ttree[i]
        try:
            nn = ttree[i+1]
        except:
            nn = {'level': -1}

        # Edge cases
        if cn['level'] > level:
            continue
        if cn['level'] < level:
            return result

        # Recursion
        if nn['level'] == level:
            result[cn['name']] = cn['value']
        elif nn['level'] > level:
            rr = ttree_to_json(ttree[i+1:], level=nn['level'])
            result[cn['name']] = rr
        else:
            result[cn['name']] = cn['value']
            return result
    return result


if __name__ == '__main__':
    ttree = fetch_levels(['A', '-B1', '--B2', '-C1', 'D'])
    result = ttree_to_json(ttree)
    print(result)

Can any help me to figure out what is wrong with the JavaScript code?

The solution is inspired by the sample code mentioned here:

Problem with removing rows with .filter JS

Database Result [
  { id: 49, absentName: 'man1', absentday: 1 },
  { id: 50, absentName: 'man2', absentday: 1 },
  { id: 49, absentName: 'man1', absentday: 2 },
  { id: 50, absentName: 'man2', absentday: 2 },
  { id: 49, absentName: 'man1', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 4 },
  { id: 50, absentName: 'man2', absentday: 3 }
]

So, absent_date and absent_days are to return the current day value, which for monday is 1.

const absent_date = new Date();
const absent_days = absent_date.getDay();

The rest:

let absent_remove = result_database.filter(item => item.absentday != absent_days);
const absent_duplicate = [...new Map(absent_remove.map(item => [item.id, item])).values()]
console.log("Absent Result", absent_duplicate);

So basically, absent_remove removes the database row if the absentday matches absent_days. I then get a bunch of duplicates which I solve with absent_duplicate, removing the duplicates. I’m left with these results down below.

Absent Result [
  { id: 49, absentName: 'man1', absentday: 3 },
  { id: 50, absentName: 'man2', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 4 }
]

Man1 and Man2 are both absent on monday (1), but they are still in the query, the question is, how do I take them out? The final result should be man3 alone.

Website full-page scroll doesn’t work properly on iphone 12 chrome browser

One day ago i added fullpage scrolling on my website (sseezov.ru) and it works fine at first look, but then i noticed that i cannot scroll properly from my wife’s Iphone – it was freezy and laggy, and only if i use Google Chrome, if i use Safari it works fine.
I don’t know what to do. Maybe i should make something with scroll lock? Please help.

Also i’m using react-swipe npm library. And i found that without fullpage scroll this carousel still freezes a little on iphone chrome. And without this carousel fullpage scroll still freezes a lot. Maybe this libraries are too old?

I use React 17, Tailwind and react-fullpage npm library.

Connecting players’ local games together

I’m looking for a special answer that i can’t find anywhere and i need your help/ideas:

The situaton:
I’m making a mobile web-game that is played on mobile phones. Every player has its own version and profile with levels etc. It is a roulette game so i want if a player gets a card it gets xp and the other players need to get xp as well. But as of now there is no way of syncing game data from one player to other players.

All roulette cards are stored in one big array and if a card is turned the script chooses a random one from the stack.

I was self thinking of some kind of code that everyone enters at the start of the game, and it contains the numbers of idk 20 cards in the array and so the game of all players will show the same card if they click next. But i dont know how to decode this and it is a bit irritating to enter such big code everytime you want to play.

P.s. i do not want to use a third party library or nodejs or something like that. Just javascript.
The “app/game” is hosted on a website that every player loads on their own phone. And game save data is stored in localstorage.

Can you please help? I dont have code to show. That is not relevant here.

Countdown repeat 48H from new date Javascript

I am trying to do a countdown in Javascript. I have the code now and it works fine, but I want to have more dates. So the first countdown is May 12, 2022 16:04:00, then I want a new 48h countdown from May 14, 2022 16:04:00, May 16, 2022 16:04:00 and so on. So when its May 12, 2022 16:04:01 I want a new 48h timer to start and countdown to May 14. Is this possible? Thanks for the help!

var countDownDate = new Date("May 12, 2022 16:04:00").getTime();

    var x = setInterval(function () {

        var now = new Date().getTime();

        var distance = countDownDate - now;

        var hours = Math.floor((distance % (1000 * 120 * 120 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.getElementById("hours").innerHTML = hours;
        document.getElementById("minutes").innerHTML = minutes;
        document.getElementById("seconds").innerHTML = seconds;

        if (distance < 0) { clearInterval(x); document.getElementById("countdown-text").innerHTML = "48H"; }
    }, 1000);
<div id="countdown">
                            <div class="countdown-hours">
                                <p id="hours"></p><span>hours</span>
                            </div>
                            <div class="countdown-minutes">
                                <p id="minutes"></p><span>minutes</span>
                            </div>
                            <div class="countdown-seconds">
                                <p id="seconds"></p><span>seconds</span>
                            </div>
                        </div>

How to color in region based on postal code using Leaflet?

I’m trying to color in an entire region on my map based on a Postal Code. So I want the entire postal code region to be colored in basically. I am using the plugin Leaflet for this.

Right now I display circles on the map (Click the link to see):
Current Map

This is the JS code I am using to display it:

   $(document).ready(function(){
        /* Initialising the map */
        var map = L.map('map').setView([50.84673, 4.35247], 9);

        L.tileLayer('https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png', {
            attribution:
            '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors' +
            ', Tiles courtesy of <a href="https://geo6.be/">GEO-6</a>',
            maxZoom: 18
        }).addTo(map);

        var popup = L.popup();

        function onMapClick(e) {
            popup
                .setLatLng(e.latlng)
                .setContent("You clicked the map at " + e.latlng.toString())
                .openOn(map);
        }

        map.on('click', onMapClick);

        // Fetching the postal codes for each representative
        $.ajax({
            url: dynamicmapurl,
            method: "GET",
            dataType: 'json',
            beforeSend: function(xhr, settings) {
                if(!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            },
            success:function(data)
            {
                data = data.reverse();

                for(var i = 0; i < data.length; i++){

                    //Drawing a circle on the map based on the
                    //Postal code dictionary array I'm receiving from the backend
                    L.circle([data[i].lat, data[i].lon], 500, {
                        color: data[i].fillColor,
                        fillColor: data[i].fillColor,
                        fillOpacity: 0.8
                    }).addTo(map).bindPopup("Vertegenwoordiger: " + data[i].vertegenwoordiger + " <br> " 
                        + " Postcode: " + data[i].postcode)
                }
            },
            error: function(data){
                console.log(data);
                alert("Algemene Error");
            }
        });
    })

Is there a way to color in the entire postal code range on the map using the Leaflet plugin? If so, how would I go about this?

Result I want: Click on link to see

*Note the region should be colored in depending on which representative & the map should not be so dark.

Thank you for helping!

How to store radiobuttons, dropdown & datepicker values at the same time to a MySQL database table using JavaScript and PHP

I am developing a survey web application that uses a set popup forms displayed one after the other as soon as a user answers the questions and click on a Next button. On one of these forms I have included radiobuttons, a dropdown box and a datepicker.

Here is my HTML code (index.php):

   <!-- form itself end-->
    <form id="form2" class="white-popup-block mfp-hide" action="" method="post">
        <div class="popup_box ">
            <div class="popup_inner">
                <h3>Enter your personal details</h3>
                <form action="index.php" method="post">
                    <div class="row">

                        <div class="col-xl-9">
                            <br>
                        </div>
                        
                        <div class="col-xl-9">
                            <div class="form-check-inline">
                                <label class="form-check-label">
                                    <input type="radio" class="form-check-input" id="radMale" name="optradio">Male
                                </label>

                                <label class="form-check-label">
                                    <input type="radio" class="form-check-input" id="radFemale" name="optradio">Female
                                </label>
                            </div>
                        </div>
    
                        <div class="col-xl-6">
                            <br>
                        </div>
    
                        <div class="col-xl-7">
                            <h4>When were you born?</h4>
                            <br>
                        </div>

                        <div class="col-xl-6">
                            <select class="form-select wide" id="default-select" class="">
                                <option data-display="Day">Day</option>
                                <option value="1">Monday</option>
                                <option value="2">Tuesday</option>
                                <option value="3">Wednesday</option>
                                <option value="4">Thursday</option>
                                <option value="5">Friday</option>
                                <option value="6">Saturday</option>
                                <option value="7">Sunday</option>
                            </select>
                        </div>
    
                        <div class="col-xl-6">
                            <input id="datepicker2" id="date" placeholder="Date of Birth">
                        </div>

                        <div class="col-xl-6">
                            <br>
                        </div>
    
                        <div class="col-xl-12">
                           <a href="#form3" class="popup-with-form">
                             <button type="submit" class="boxed-btn3" onclick="customFunction()">Next</button>
                            </a>
                        </div>
                        <div class="col-xl-12">
                            <br>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </form>
    <!-- form itself end -->

This is the JavaScript code (within index.php):

 <script>

      function customFunction() {
       
          var gender = document.querySelector('input[name=optradio]:checked').value;
          var Day = document.getElementById("default-select");
          var daySelected = Day.options[Day.selectedIndex].value;
          var DateOfBirth = document.getElementById("date").innerHTML = today;

      
        if (gender != null && gender !="" && daySelected != null && daySelected !="" && DOB != null && DOB !="") {
            
          $.post("insert.php", { gender: gender , daySelected : daySelected , DateOfBirth : DateOfBirth },function(response){
             console.log(response);
         });
            
        }
     } 
</script>

This JavaScript code was basically used to call the insert.php file that would store all the 3 different values in a database table.

Here is the insert.php file:

<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "persons";
// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

$gender = isset($_POST['gender'])?$_POST['gender']:''; 
$Day = isset($_POST['daySelected'])?$_POST['daySelected']:'';
$Date = isset($_POST['DateOfBith'])?$_POST['DateOfBirth']:'';

$sql = "INSERT INTO info (Gender, Day, DOB) VALUES ('".$gender."' , '"$Day"', '"$Date"')";

if ($conn->query($sql) === TRUE) { 

   echo "New record created successfully"; 

} else { 

   echo "Error: " . $sql . "<br>" . $conn->error; 

} 

$conn->close(); 

?> 

The issue I have is that I cannot store any of these 3 values (e.g radiobutton, dropdown and datepicker) in the database table. Can anyone help me to do this please?

When I truing to use some js libraries with no d.ts I have errors

So for example I want to use a cottonjs (dont have a d.ts file) library. And in angular.json O twice write

 "scripts": ["../node_modules/cottonjs/cotton.js"]

and in my component I tried to declare it

import {Component, OnInit} from '@angular/core';
declare var Cotton:any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit() {
    console.log(Cotton)
  }
}

But every time when I tried to use some libraries in console I see this:

ERROR ReferenceError: Cotton is not defined
    at AppComponent.ngOnInit (app.component.ts:11:17)
    at callHook (core.mjs:2542:1)
    at callHooks (core.mjs:2511:1)
    at executeInitAndCheckHooks (core.mjs:2462:1)
    at refreshView (core.mjs:9501:1)
    at renderComponentOrTemplate (core.mjs:9600:1)
    at tickRootContext (core.mjs:10854:1)
    at detectChangesInRootView (core.mjs:10879:1)
    at RootViewRef.detectChanges (core.mjs:21491:1)
    at ApplicationRef.tick (core.mjs:26563:1)

P.s dont work there too
Heeeeeeeelp please

unable to catch any form of error or response from firebase notification callback function in Node js

I am using the package “fcm-node” in order to send notifications to certain device id.

the sendNotification function is as follows:

const FCM = require('fcm-node');
const serverKey = process.env.SERVER_KEY;
const fcm = new FCM(serverKey);

function sendNotification(registrationToken, title, body, type, key) {
    const message = {
        to: registrationToken,
        collapse_key: key,
        notification: {
            title: title,
            body: body,
            delivery_receipt_requested: true,
            sound: `ping.aiff`
        },
        data: {
            type: type,
            my_key: key,
        }
    };
    fcm.send(message, function (err, value) {
        if (err) {
            console.log(err);
            return false;
        } else {
            console.log(value);
            return value;
        }
    });
};

module.exports = {
    sendNotification
};

The api function I use to call this function is as follows:

router.get('/test', async (req, res, next) => {
  const promise = new Promise((resolve, reject) => {
    let data = sendNotification('', 'dfsa', 'asds', 'dfas', 'afsdf');
    console.log(data)
    if (data == false) reject(data);
    else resolve(data);
  });
  promise
    .then((data) => { return res.status(200).send(data); })
    .catch((data) => { return res.status(500).send(data) })
});

When I console.log the “err” and “value” from the sendNotification, I get either of the followings:

{"multicast_id":4488027446433525506,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1652082785265643%557c6f39557c6f39"}]};

{"multicast_id":8241007545302148303,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

In case it is successful, I made sure that the device is receiving the notification.

The problem is in the api’s data. It is always “undefined” and weither send notification is successful or not I get the 200 Ok status.

What seems to be the problem?

Pass JSON array to function in React as props and then count items in area

Apologies. Newbie here having problems with passing a JSON object into a function as props. I’m obviously doing something wrong but I’ve searched and other people’s posts seem more complex than mine.

I want to pass an array which may have zero or more rows into a function and then I want to count how many rows there are. Finally I would return a string depending on that. I’ve got the last part working but I can’t pass the array without getting undefined.

App.js

const sampleTeams = [
  {
    team: "Jets",
    season: "2022/23",
    regfee: 35,
    feepaid: true,
  },
];

function App() {
  return (
    <Container className="my-4">
    <MemberCard
      forename="Bob"
      surname="Jones"
      playerNumber="154"
      registrations={sampleTeams}
    ></MemberCard>
    </Container>
  );
}

MemberCard.js

export default function MemberCard({
  forename,
  surname,
  memberNumber,
  registrations,
}) {
  return (
    <Card>
      <Card.Body>
        <Card.Title className="d-flex justify-content-between slign-items-baseline fw-normal mb-3">
          <div className="me-2">
            {forename} {surname}
          </div>
          <div className="d-flex align-items-baseline text-muted fs-6 ms-1">
            {memberNumber}
          </div>
        </Card.Title>
        <p>{getNumberOfTeams({ registrations })} registered</p>
        <Stack direction="horizontal" gap="2" className="mt-4">
          <Button variant="outline-primary" className="ms-auto">
            Register Team
          </Button>
        </Stack>
      </Card.Body>
    </Card>
  );
}

function getNumberOfTeams(registrations) {
  const numberOfTeams = registrations.length;
  // console.log(numberOfTeams);
  if (numberOfTeams === 1) return "1 team";
  return numberOfTeams + " teams";
}

adding an hover effect for each item in a mapped variable

I have this variable with items

const tabContent = [
{
    Describtion1 : "Chief. Mordy Wenk",
    Describtion2 : "ChiefDescribtion-1",
     Title : "Head of the Chief staff.",
    Img : "https://user-images.githubusercontent.com/86873404/156891438-ab14a39b-53a9-4940-892c-b0bbe74d6acf.png"
},{
    Describtion1 : "Chief. Mark Brunnett",
    Describtion2 : "ChiefDescribtion-2 ",
     Title : "Junior chef.",
    Img : "https://user-images.githubusercontent.com/86873404/165656553-7f853d16-ac1b-4880-ad5e-7943767811e5.png"
},{
    Describtion1 : "Chief. Griffin Zach",
    Describtion2 : "ChiefDescribtion-3",
     Title : "a Talented Chef.",
    Img : "https://user-images.githubusercontent.com/86873404/165656971-8911df46-68a3-4311-ab75-c57e57ba5e19.png"
},{
    Describtion1 : "Chief. Will Smith",
    Describtion2 : "ChiefDescribtion-4",
     Title : "a Talented Chef.",
     Img : "https://user-images.githubusercontent.com/86873404/165657351-cb095c73-588e-49bd-a4ce-119ff721a3ed.png"
    }]

then I used a useState to make a rotate effect whenever I hover on the container

    const [pizzaMoves, setPizzaMoves] = useState({transform:"translate(40px,0)"})
    const [pizzaMoves2, setPizzaMoves2] = useState({transform:"translate(-40px,0)"})

and I mapped over it like this

{tabContent.map(item => (
            <Center>
                <SwiperSlide>
            <Box 
            borderRadius={"50%"}
            onMouseEnter={e => {
                setPizzaMoves2({transform:"translate(10px,0) rotate(90deg) scale(1.1)"})
            }}
            onMouseLeave={e => {
            setPizzaMoves2({transform:"translate(-40px,0)"})
        }}>
                <Box
                onMouseEnter={e => {
                    setPizzaMoves({transform:"translate(-10px,0) rotate(90deg) scale(1.1)"})
                }}
                onMouseLeave={e => {
                    setPizzaMoves({transform:"translate(40px,0)"})
                }}
                w="400px"
                borderRadius={"30px 30px 0% 0%"}
                boxShadow="rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;"
                transition="0.3s"
                _hover={{ transform:"scale(1.025)",
                    boxShadow:"rgba(0, 0, 0, 0.25) 0px 54px 55px, rgba(0, 0, 0, 0.12) 0px -12px 30px, rgba(0, 0, 0, 0.12) 0px 4px 6px, rgba(0, 0, 0, 0.17) 0px 12px 13px, rgba(0, 0, 0, 0.09) 0px -3px 5px;"}}
                marginTop={"80px"}
                backgroundColor="#461111" 
                backgroundImage="https://www.transparenttextures.com/patterns/gradient-squares.png"
                >
                    <Box 
                    boxShadow={"rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;"}
                    borderRadius={"30px 30px 0% 0%"}
                    p="0px 30px"
                    backgroundColor="#050200"
                    w="100%"
                    backgroundImage="https://www.transparenttextures.com/patterns/gradient-squares.png"
                        >
                        <HStack justifyContent={"center"} align={"flex-end"}>
                            <Image w="75px" style={pizzaMoves2} transition="0.3s ease"
                            transform={"translate(-40px,0)"} src="https://user-images.githubusercontent.com/86873404/166059070-6a6826b1-0ef2-43f4-b242-0da7e3abeff6.png"/>
                            <Image w="150px" borderRadius={"50%"} src="https://user-images.githubusercontent.com/86873404/165981282-19b7041f-26c7-40e5-94a5-d61f305bf8a2.png"/>
                            <Image w="75px" style={pizzaMoves} transition="0.3s ease"
                            src="https://user-images.githubusercontent.com/86873404/166059070-6a6826b1-0ef2-43f4-b242-0da7e3abeff6.png"/>
                        </HStack>
                    </Box>
                    <VStack p="30px">
                        <HStack>
                        <Text 
                        fontSize={30}
                        fontFamily={"'Josefin Sans', sans-serif;"}
                        color={"white"}
                        >{item.Describtion1}</Text>
                        </HStack>
                        <Text fontFamily="'Boogaloo', cursive;" fontSize={"18px"}
                        color="#fff700">
                            {item.Title}
                        </Text>
                        <Text
                        color={"white"}
                        w="300px"
                        fontFamily={"'Josefin Sans', sans-serif;"}
                        >
                            {item.Describtion2}
                        </Text>
                        </VStack>
                </Box>
                </Box>
                </SwiperSlide>
                </Center>
        ))}

so like this , whenever I hover on the container It rotates all the images not only the image that I hovered its’ container, so how can I be able to only do one image at a time?

Svelte only supports es6+ syntax. Set your ‘compilerOptions.target’ to ‘es6’ or higher

I have been using Svelte, TypeScript and Rollup (letting TypeScript handle the transpilation) to target ES7. Now I’m starting a new project and need to target ES5.

The first thing I have noticed is that everything gets transpiled but components are still classes. I didn’t have any scripts in the components at that point. Once I added a script tag to .svelte file, I immediately got the error:

Svelte only supports es6+ syntax. Set your ‘compilerOptions.target’ to ‘es6’ or higher

I understand that I will need to set TS target to ES6/ES7 and install Rollup Babel plugin to handle the transpilation to ES5. But why would plain TypeScript transpilation not work? Why Svelte cares about TypeScript target? You’d think that Svelte files get converted to TS before being transpiled to ES5, but it seems like it’s the other way around?