JavaScript – Generate a random number between 1 and 30, six times

we’ve been given this problem in a coding Bootcamp and I cannot for the life of me work out how to do it – any help would be greatly appreciated.

“Generate a random number between 1 and 30, six times.

For each random number generated, check if
this number of divisible by 7 or not.

Log out a message to the console if it is divisible
by 7 or not.”

How to use Leaflet to create interactive map which allows user to select country or territory and produce a popup with text on it?

My goal is to create an interactive map where its user can click or tap anywhere within a country or territory’s legally recognised borders, causing a pop up to appear. A big enough red circle will appear for countries/ territories which are too small to select. I have no idea on how to accomplish this.

Anyway, I created one, with pins instead and it looks awful.

Please give me advice on this.

filter does not show results when you search again React hooks

i’m trying to filter the data, but the problem is, it doesn’t show results when you search again. so any idea what’s wrong in my code. Thanks in advance

const results = users?.map(singleUser => {
    singleUser.websites = singleUser.websites.filter(network =>
      network.name.toLowerCase().includes(search.toLowerCase())
    );

    const items = singleUser[dataKey]?.map((listItem) => {
      return (
        <ListItem>
             <Highlighter
              searchWords={[search]}
              textToHighlight={items.name}
            />
        </ListItem>
      );
    });

    return (
      singleUser.networks.length !== 0 && (
        <Accordion>
          <section>
            <ListAccordionList>{items}</ListAccordionList>
          </AccordionDetails>
        </Accordion>
      )
    );
  });

  return (
    <Grid>
      {results}
    </Grid>
  );
}

How to use condition for adding or removing closing tags containing htms in JSX?

Fade tag which is animation tag under package react-reveal
I want to use Fade tag for the animation only when my mouse come under div tag else I don’t want to animate the div className=card-container but
to do this I have to repeat the code div className=card-container like so
{ isHover ? <Fade>div className="card-container"</Fade> : div className="card-container" }

Is there alternative to do remove Fade tag only in simple way.

import React from "react";
import styled from "styled-components";
import { Fade } from "react-reveal";


export default function CardSection() {
    const [isHover, setIsHover] = React.useState(false);

    function getIsHover() {
        setIsHover((prev) => !prev);
    }

    return(
        <CardSectionStyled>
            <div onMouseEnter={getIsHover}>
                <div className="card-container">
                    {/* Here I have to repeat p tag in order to add and remove Fade tag  */}
                    {isHover ? <Fade right duration={1500} delay={500}>
                        <div className="card-left">
                            <p>
                                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab 
                            </p>
                        </div>
                    </Fade> :
                        <div className="card-left">
                            <p>
                                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab
                            </p>
                        </div>
                    }
            </div>
        </CardSectionStyled>
    );
}

const CardSectionStyled = styled.section`
    .card-container {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
    }

    p {
      padding: 1.5rem 0;
    }
`;

Uncaught ReferenceError: google is not defined // VueJS 3

i want to learn to insert a external script like google maps into my vuejs component.

First of all, i have create the script tag and load in beforeMounted() to add to my page DOM.

  beforeMount() {
    const script = document.createElement('script');
    script.async = true;
    script.defer = true;
    script.src = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&callback=${CALLBACK_NAME}`;
    script.onerror = rejectInitPromise;
    document.querySelector('head').appendChild(script);
  }

Second, create a function startLoading() which is called in my mounted() section.

methods() {
  startLoding() {
    const google = new google.maps.Geocoder();
    console.log(google)
  }
},
mounted() {
  this.startLoding()
}

This code snippet above not work because “Uncaught ReferenceError: google is not defined”

If i store the new.google.maps.Geocoder() in a setTimeout it works

methods() {
  startLoding() {
    setTimeout(function() {
      const google = new google.maps.Geocoder();
      console.log(google)
    }
  }
},
mounted() {
  this.startLoding()
}

So my question: how do i have to load the google script that my vue component can use the functions without an setTimeout?

Console object replacing not working in javascript

I have replaced the console object with the below code. My intention is to get all the logs written to the console and pass those to my logger component for sending to server
But when I tested it very few logs are passed to the logger component. Please help me identify the issue?

In the below code I have overridden almost all the functions in the console object.
Is there a chance that the browser provides different console objects for different components within the same app?

var console = (function (oldCons) {
  return {
    log: function () {
      var msg = '';
      for (var i = 0; i < arguments.length; i++) {
        msg += '--' + arguments[i];
      }
      oldCons.log('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.logError("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from log-------------" + msg);
    },
    info: function () {
      var msg = '';
      for (var i = 0; i < arguments.length; i++) {
        msg += '--' + arguments[i];
      }
      oldCons.info('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.logError("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from info-------------" + msg);
    },
    warn: function () {
      var msg = '';
      for (var i = 0; i < arguments.length; i++) {
        msg += '--' + arguments[i];
      }
      oldCons.warn('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.logError("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from warn-------------" + msg);
    },
    error: function () {
      var msg = '';
      for (var i = 0; i < arguments.length; i++) {
        msg += '--' + arguments[i];
      }
      oldCons.error('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.logError("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from error-------------" + msg);
    },
    assert: function () {
      var msg = '';
      var tmp = '';
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === 'object') {
          tmp = JSON.parse(JSON.stringify(arguments[i]));
        } else {
          tmp = arguments[i];
        }
        msg += '--' + tmp;
      }
      oldCons.log('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.logError("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from error-------------" + msg);
    },
    clear: function () {
    },
    count: function () {
    },
    countReset: function () {
    },
    dir: function () {
      var msg = '';
      var tmp = '';
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === 'object') {
          tmp = JSON.parse(JSON.stringify(arguments[i]));
        } else {
          tmp = arguments[i];
        }
        msg += '--' + tmp;
      }
      oldCons.log('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.logError("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from error-------------" + msg);
    },
    dirxml: function () {
    },
    group: function () {
    },
    groupCollapsed: function () {
    },
    groupEnd: function () {
    },
    table: function () {
    },
    time: function () {
    },
    timeEnd: function () {
    },
    timeLog: function () {
    },
    time: function () {
    },
    timeEnd: function () {
    },
    debug: function () {
      var msg = '';
      for (var i = 0; i < arguments.length; i++) {
        msg += '--' + arguments[i];
      }
      oldCons.error('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.debug("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from error-------------" + msg);
    },
    trace: function () {
      var msg = '';
      for (var i = 0; i < arguments.length; i++) {
        msg += '--' + arguments[i];
      }
      oldCons.trace('JJJJJJJJJJJJJJJJJJJJJ -----------' + msg);
      logger.logError("CN", "__oraco__route_c-start", "processRouteIdFromRouteAllocation()", "This is from error-------------" + msg);
    }
  };
}(window.console));

window.console = console;

Confused about blocking operation’s execution JavaScript i.e (execution order)

async () => {
try {
  setTimeout(() => console.log('next task'), 0);
  await timeTakingFunc();
  console.log('after waiting for timetaking function');
} catch (error) {
  console.log(error.message);
}})();

OUTPUT:
after waiting for timetaking function
next task


shouldn’t ‘next task’ be printed first as timeTakingFunction(); is taking long time to execute and timeout is only 0ms?

how to active a link as default to pass parameters to route

I configured my app in two levels for nested routing as shown in the snapshot image.
enter image description here

the content of app modules is:
app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    TeacherMembershipComponent,
    StudentMembershipComponent,
    RulesComponent,
    ContactInfoComponent,
    Page404Component,
    UserProfileComponent,
    NotificationsComponent,
    GeneralComponent,
    ReportComponent
  ],
// ...

and app-routing.module.ts

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent
  },
  {
    path: 'userProfile',
    component: UserProfileComponent
  },
  {
    path: 'general',
    component: GeneralComponent
  },
  {
    path: 'report',
    component: ReportComponent
  },
  {
    path: 'notifications',
    component: NotificationsComponent
  },
  {
    path: "department/:dep", loadChildren: () => import(`./branches/branches.module`).then(m => m.BranchesModule)},
  {
    path: 'aboutUs/rules',
    component: RulesComponent
  },
  {
    path: 'aboutUs/contactInfo',
    component: ContactInfoComponent
  },
  {
    path: 'membership/teacher',
    component: TeacherMembershipComponent
  },
  {
    path: 'membership/student',
    component: StudentMembershipComponent
  },
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: '**', component: Page404Component },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

the second level is branches that its modules are:

branches.module.ts:

@NgModule({
  declarations: [
    BranchesComponent,
    CoursesListComponent,
    TeachersListComponent,
    TeacherResumeComponent,
    TeacherSelectionFormComponent,
    Page404BranchesComponent
  ],
  imports: [
    CommonModule,
    BranchesRoutingModule,
    MaterialDesignModule
  ]
})
export class BranchesModule { }

and branches-routing.module.ts:

const routes: Routes = [
  { path: '', component: BranchesComponent, children: [
     {
      path: "coursesList/:branchCourses",
      component: CoursesListComponent
     },
    {
       path: "teacherSelection",
       component: TeacherSelectionFormComponent
    },
     {
      path: "teacherResume",
      component: TeacherResumeComponent
    },
      {
        path: 'coursesList', component: CoursesListComponent
      },
    {
      path: '', redirectTo: 'coursesList', pathMatch: 'full'
    },
    {
      path: '**', component: Page404BranchesComponent
    },
   ]}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

till here, when one of links (departments) in sidenav of app.component.html is clicked, the branches.component is loaded in place of route-outlet of app.component and subscribes the parameters passed from app.component, and lists branches respected to each link.

baranch.component.ts:

export class BranchesComponent implements OnInit {

  filteredBranches$!: Observable<Branch[]>;
  filteredBranches!: Branch[];

  constructor(private route: ActivatedRoute, private branchesService: BranchesService) {
  }

  activeTab: string=''
  ngOnInit(): void {
    this.route.paramMap.pipe(
      switchMap((params: Params) => {return this.branchesService.getDepBranches(params['get']('dep')) })
    ).subscribe((branches) => {this.filteredBranches = branches; this.activeTab=this.filteredBranches[0].name});
  }
}

and branch.component.html:

<nav mat-tab-nav-bar>
  <a mat-tab-link *ngFor="let br of filteredBranches"
     [routerLink]="['coursesList', br.code]"
     routerLinkActive="activeLink"
     (click)="activeTab = br.name"
     [active]="activeTab == br.name"> {{ br.name }} </a>
</nav>

<router-outlet></router-outlet>

but, although links of branches are listed in template of branches.component, no courses respect to each branches are shown by coursesList.component which placed in router-outlet of branches.component, because it does not received any route parameter from branch.component, until one of branch link is clicked.
I expect that upon branches links are shown at the same time branches.component is loaded, bellow of them, the courses of the first branch are listed by coursesList.component placed in router-outlet of branches.component.
Whereas no one of branch links is clicked and no parameter passed to coursesList.component, nothing is shown. Therefore, is there a solution to active the first branch link as defualt and pass its courses parameters to coursesList component upon branches.component is loaded? Best regards.

Writing repeated jsx vs making an array or object in react. Which approach is the best?

If we are making an array or an object… that is also gonna take memory space and if we write the same jsx again and again.. that is also going to affect on our performance.
For Example.
Let’s say I have a list of (1,2,4,5,6) and I want to show them in a span tag as a list.
I have two choices.
1: I can repeat the same jsx and write out 6 spans and type static data in it.
2: I can make an array and store the numbers in it and run a loop on it.
Now here I want to know which is the best.

Converting HTML to text in NodeJs (outside of the browser)

How do you convert html to text efficiently using NodeJS, i.e. outside of the browser? I also want to convert entities like &auml; to ä, etc and not only just remove tags from the html.

Here is a JEST unit test for a a function convertHtmlToText which does this conversion:

it('when extract from partial html should extract text', () => {
  const html = `<p>&nbsp;&auml;&uuml;
t<img alt="" src="http://www.test.org:80/imageupload/userfiles/2/images/world med new - 2022.jpg" style="width: 2000px; height: 1047px; max-width: 100%; height: auto;" /></p>
<p>
tAn evening of music, silence and guiding thoughts to help us experience inner peace, connect with the Divine and share loving vibrations with the world. Join millions of people throughout the world to contribute in creating a wave of peace.</p>
<div>
t&nbsp;</div>
<div>
t<strong>Please join ....</strong></div>
<div>
t&nbsp;</div>
<div>
t<strong>Watch live:&nbsp;<a href="https://test.org/watchlive" target="_blank">test.org/watchlive</a></strong></div>`
  const text = convertHtmlToText(html)
  console.log(text)
  expect(text).toContain("ä");
  expect(text).toContain("ü");
  expect.not.stringContaining("<")
  expect.not.stringContaining(">")
});

How validate the dates?

I am comparing the dates wherein the next object created should not have the dates between the date present in my database objects. For that, I have created a validation

 $scope.shiftTypeValues.forEach(function (shift) {
                    if ((shift.endDate >= item.endDate || shift.endDate >= item.startDate)) {
                        window.alert("There is another shift between that date! Please select another shift");
                        found = true;
                    }
            });

Here, $scope.shiftTypeValues are the objects in my database and item are the current object for which I am checking the date. Right now I am comparing the end dates with the current item start date and end date but suppose I save the date as

    Start Date              End Date
1.) Feb 16,2022             Feb 19,2022
2.) Feb 20,2022             Feb 24,2022

Now, if I edit the first date and save the date as 18Feb,2022 which should save since there is no shift falling under that date but my condition is checking the end date so 24 feb > 19 feb and it is showing alert? So, what should I check in order to save my object?

find index of 2 dimensional array in javascript

I want to get the index of a array which contains a specific item

this is my code:

const array1 = [
  [5, 2, 1],
  [12, 12, 12],
  [8],
  [130],
  [44]
];


console.log(array1.findIndex((item) => {
  typeof item.find((it) => {
    return it == 5
  }) !== 'undefined';
}));

i tried this to get the index of the array which contains a specific element but i always get index -1.

AskJS : Embed a condition to add “.append” if a condition is met

I want to nest a condition in a block with “.append” statements but I don’t know how. Indeed I want to add a formatting if the conditions are true.

How can I do ?
The code is not great but it does the trick for a layout plugin for REDMINE…

A piece of code and in yellow where I want to add a condition

  // Variables pour les conditions
  const IssueDemandeId = $('#issue_custom_field_values_10').val();
  
  if (IssueDemandeId !== '')
 {
$('.description')
.before(
 $('<div class="splitcontent">')
 // Détails de la demande CORIM
  .append($('<div class="splitcontent">').append(Header2))
  .append($('<div class="splitcontent">').append(CorimField1))
  .append($('<div class="splitcontent">').append(CorimField10))
  .append($('<div class="splitcontentleft">').append(CorimField11))
  .append($('<div class="splitcontent">'))
  .append($('<div class="splitcontent">').append(CorimField4))
  .append($('<div class="splitcontentleft">').append(CorimField3))
  .append($('<div class="splitcontentleft">').append(CorimField2))
  .append($('<div class="splitcontentleft">').append(CorimField12))
  .append($('<div class="splitcontentleft">').append(CorimField13))
  .append($('<div class="splitcontent">'))
  .append($("<br></br>"))
  .append($('<div class="splitcontent">').append(MiddleHeader3))
  .append($('<div class="splitcontent">'))
  .append($('<div class="splitcontentleft">').append(CorimField5))
  .append($('<div class="splitcontentleft">').append(CorimField6))
  .append($('<div class="splitcontentleft">').append(CorimField7))
  .append($('<div class="splitcontentleft">').append(CorimField8))
  .append($('<div class="splitcontentleft">').append(CorimField9))
  .append($('<div class="splitcontent">'))
  .append($("<p></p><hr>"))
  // Détails de la demande Esupport
  .append($('<div class="splitcontent">').append(Header1))
  .append($('<div class="splitcontent">').append(MiddleHeader1))
  .append($('<div class="splitcontentleft">').append(EsupportField1))
  .append($('<div class="splitcontent">').append(EsupportField2))
  .append($('<div class="splitcontentleft">').append(EsupportField3))
  .append($('<div class="splitcontent">').append(EsupportField4))
  .append($('<div class="splitcontent">').append(EsupportField5))
  .append($("<br></br>"))
  .append($('<div class="splitcontent">').append(MiddleHeader2))
  .append($('<div class="splitcontent">').append(EsupportParcField1))
  .append($('<div class="splitcontentleft">').append(EsupportParcField2))
  .append($("<br></br>"))
  .append($("<p></p><hr>"))


  //Embed a condition to add ".append" if a condition is met

);
 }
 
 )

Impossible to get the URL of a tab with chrome extension (manifest v3)

I’ve been struggling for a long time with Chrome Extensions. How do I get the URL of the tab from background.js (my service worker) ?

It seems like a very easy thing to do but……..

// manifest.json
{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html"
  }
}
// background.js
chrome.tabs.onActivated.addListener(activeInfo => {
  chrome.tabs.get(activeInfo.tabId, (tab) => {
    // tab.url is undefined, it should not.
  });
});

it doesn’t work. why ?