Javascript arrays better performance

I have an array of objects (myObjsArr). The object contains 2 methods:

obj: {
   getUserId(), // returns a string. For instance, "123"
   getSubUserIds(), // returns an array of strings. For instance, ["abc", "abc2", ...]
}

I’m looping this array of objects to create 2 arrays.

  1. Array of user ids
  2. Array of sub user ids.
const userIds = [];
const subUserIds = [];

myObjsArr.forEach((obj) => {
   userIds.push(obj.getUserId());
   obj.getSubUserIds(element => {
      subUserIds.push(element);
   })
});

This works, but seems not efficient. How could I improve my code?

Thanks

Lodash typescript – Combining multiple arrays into a single one and perform calculation on each

I have a Record<string, number[][]> and trying to perform calculation over these values.

An example input:

   const input1 = {
      key1: [
        [2002, 10],
        [2003, 50],
      ],
    };
    const input2 = {
      key1: [
        [2002, 20],
        [2003, 70],
      ],
    };
    const input3 = {
      key1: [
        [2002, 5],
        [2003, 60],
      ],
    };

For each key, and for the specific year I want to do the following

year => input1 + input2 - input3
// output: 2002 => 25, 2003 => 60

For this I have been playing around with lodash/fp.

map(a => a.map(nth(1)))(map('asset1')([input1, input2]))
// [[10, 50], [20, 70], [5, 60]]

is there a way to somehow pass the inputs and iterate over them, and somehow get a callback function to get the values to perform the calculation.

I tried zip, zipWith but didn’t get to anywhere with them.

Any clue what I can do in this instance?

Thank you for your help.

Is Test Driven Development necessary all the time?

I am learning how to write tests in Javascript and I want to be clear on some things. Please permit me because I’m completely new to the TDD game.

  1. I have a blue button that when clicked performs an action. I have manually tested the button by clicking on it with the mouse and I can confirm that the operation it was meant to perform was actually performed. So, what then is the extra benefit of writing tests to check if the click on the button worked even though I’ve manually tested for that?

  2. If a programmer is imperfect enough to write bad code, is there any chance he will write better tests. Won’t there be bias?

  3. Is it necessary I test every single function in my code?

  4. Sometimes I see quite alot of bugs even in big tech company apps. I believe they wrote tests, yet such bugs were still shipped to production. Does it mean their engineers didn’t test enough before deployment?

Thanks

How generate uniques grouping/summing one of the columns based on 2 criteria in Javascript?

I’ve been trying to get this one, but it’s still hard for me.

The data:

let data = [
 [1, "Item A", "Food", 10],
 [2, "Item B", "Food", 5],
 [3, "Item C", "Food", 30],
 [4, "Item A", "Hygiene", 30],
 [4, "Item A", "Hygiene", 50],
 [6, "Item D", "Food", 7],
 [3, "Item C", "Food", 8],
 [1, "Item A", "Food", 60],
]

Result

let result = [
 [1, "Item A", "Food", 70],
 [2, "Item B", "Food", 5],
 [3, "Item C", "Food", 38],
 [4, "Item A", "Hygiene", 80],
 [6, "Item D", "Food", 7],
]

This is basic reduce() which I imagine would be the path to take, but how to set the criteria e generate unique rows?

const array1 = [1, 2, 3, 4];
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);
console.log(sumWithInitial);

Appreciate your help!

JSON data printing issue in react-js

This is my JSON Data

const Paper = [{ Head: "<strong>Heading Content</strong>sub-heading", content: ["sample texts...."] }];

And i try to print this data to my page it working but it show like <strong>Heading Content- </strong>subheading

{Paper.map((Paper) => (
  <div className='news-papper'>
    {Head}
  </div>
))}

I wand ” Heading Content- subheading ”
How to print data like this?

Why an array cannot be sorted in both ascending and descending in a single block of code/function?

Why do ascending and descending arrays give the same output? Anyone can solve this?

function isSortedAndHow(arr) {
  let asc = arr.sort((a, b) => a - b); // Ascending order , yes
  let dsc = arr.sort((a, b) => b - a); // descending array, yes

  if (arr == asc) {
    console.log("Ascending , Yes");
  } else if (arr == dsc) {
    console.log("Descending , Yes");
  } else {
    console.log("No");
  }
}
isSortedAndHow([25,20,15,30,35]);

swiper.destroy() is not working when have multiples sliders on a page

I have a bunch os swiper instances in the same page and need to destroy/init them based on screen width:

const mobile = window.matchMedia('(max-width: 575.98px)');

function instantiateGridSlider() {
const sliders = [];
$('.thumbnails-grid').each(function(index, element){
    const instance = $(this).data('instance');
    sliders[index] = new Swiper(element, {
    speed: 500,
    spaceBetween: 30,
    slidesPerView: 1,
    loop: true,
    init: false,
    pagination: {
        el: '.swiper-pagination-' + instance,
        type: 'bullets',
        clickable: true,
    },
    });
});

return sliders;
}

function initGridSlider() {
if ($('.thumbnails-grid').length == 0) {
    return;
}

const gridSliders = instantiateGridSlider();
for (let i = 0; i < gridSliders.length; i++) {
    if (mobile.matches) {
    gridSliders[i].init(gridSliders[i].el);
    } else {
    gridSliders[i].destroy(true, true);
    }
}
}

window.addEventListener('resize', function() {
initGridSlider();
});

initGridSlider();

But I’m getting this error when resize the windows to destroy the sliders:

Uncaught TypeError: Cannot read properties of undefined (reading
‘children’)
at Swiper.loopDestroy (loopDestroy.js:6:1)
at Swiper.destroy (core-class.js:545:1)
at initGridSlider (slider.js:84:1)
at slider.js:90:1

Can I combine these functions into one streamlined function?

I am swapping out background images on click for several different instances, and also only targeting screens at 991px and above. Can I create one, streamlined function or make this more concise/better?

const mediaQuery = window.matchMedia('(min-width: 991px)')
const infraTab1 = document.querySelector(".content1")
const infraTab2 = document.querySelector(".content2")
const infraTab3 = document.querySelector(".content3")
const infraTab4 = document.querySelector(".content4")
const infrastructure = document.querySelector(".infrastructure")

if (mediaQuery.matches) {

  infraTab1.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(https://www.tcenergy.com/siteassets/home/infrastructure/tc-infrastructure-ng-bg-desktop.jpg)";
  })
}
if (mediaQuery.matches) {
  infraTab2.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(https://www.tcenergy.com/siteassets/home/infrastructure/tc-infrastructure-power-bg-desktop.jpg)";
  })
}
if (mediaQuery.matches) {
  infraTab3.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(https://www.tcenergy.com/siteassets/home/infrastructure/tc-infrastructure-liquids-bg-desktop.jpg)";
  })
}
if (mediaQuery.matches) {
  infraTab4.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(https://www.tcenergy.com/siteassets/home/infrastructure/tc-infrastructure-decarb-bg-desktop.jpg)";
  })
}

Using NumeralJS, how can I determine the format based on whether a number is thousands or millions

My header pretty much sums it up, in my application Im formatting a value only when the value is greater than 6 digits. When the value is thousands, e.g. 210,500, I want to display it as 210.5k, if the value is in the millions, e.g. 2,120,000, I want to display it as 2.12m. Currently the format string (‘0,0.[00]a’) will display both of these numbers to both decimal place(s), but I’d like that to be determined based on the whether or not the value is thousands or millions

Is the best way to figure this out to loop through the value until a decimal is reached and then determine the formatting based on that number? I have tried using the Custom Format object but am having a hard time understanding what’s happening under the hood.

How can I rune getServerSideProps con funcitonal component with Nextjs?

Is possible to run the server side props within a component in NextJS?
As I understand, getServerSideProps fetches the data when entering into my page, but, is possible for it to run when rendering a component?

This is because I have the following:

export default function FichaTecnica(props) {
  const indicador = props.data;

  const crumbs = [{
    text: 'Chihuahua en Datos',
    href: '/chihuahua-en-datos'
  }, {
    text: indicador.modulo.temaIndicador,
    href: `/chihuahua-en-datos/temas/${indicador.modulo.id}/indicadores`
  }, {
    text: indicador.nombre
  }];

  return (
    <>
      <Container sx={{ mb: 3, mt: 3 }}>
        <PageBreadcrumb crumbs={[...crumbs]} />
        <TopData info={indicador} />
        <DataSheet datasheet={indicador} />
        <GraphBox history={indicador} />
        <MapButton mapa={indicador.mapa} />
        <IndicadorOwner authorID={indicador.createdBy} indicadorDate={indicador.updatedAt} />
      </Container>
    </>
  );
}

export async function getServerSideProps(context) {
  const idIndicador = context.params.idIndicador;
  const res = await fetch(
    `${process.env.INDICADORES_BASE_URL}/indicadores/${idIndicador}`
  );

  const data = await res.json();

  if (res.status === 200) {
    return {
      props: { ...data },
    };
  } else {
    return {
      props: {
        data: [],
      },
    };
  }
}

I want to fetch data on the IndicadorOwner component, and inside of it I have:

const IndicadorOwner = ({ ownerID, indicadorDate }, props) => {
    return (
        <>
            <Title variant='h4' component='h2'>Responsable</Title>
            <Grid container className={`${style.indicadorOwner}`}>

                <Grid item sm={12} md={8} lg={6} xl={6} className={`${style.cardBody}`}>
                    <Box className={`${style.cardContainer}`}>
                        <Box className={`${style.imageContainer}`}>
                            <Avatar alt='Bobby P.' src='https://media.gq.com.mx/photos/61f8318a45749103d307bf61/2:3/w_1124,h_1686,c_limit/robert%20pattinson.jpg' sx={{ width: 100, height: 100 }}>
                            </Avatar>
                        </Box>
                        <Box className={`${style.userInformation}`} >
                            <Typography variant='caption' component='h4' className={`${style.cardData}`}>
                                24 de Julio 2022
                            </Typography>
                            <Typography variant='subtitle' component='h3' className={`${style.cardData}`}>
                                Robert Pattinson
                            </Typography>
                            <Typography variant='subtitle' component='h5' className={`${style.cardData}`}>
                                Robert Douglas Thomas Pattinson (born 13 May 1986) is an English actor. Known for starring in both big-budget and independent films.
                            </Typography>
                            <br />
                        </Box>
                        <Box className={`${style.contact}`}>
                            <Link href='mailto:[email protected]' className={`${style.link}`}>
                                <Avatar sx={{ width: 30, height: 30 }} className={`${style.emailIcon}`}>
                                    <MailIcon />
                                </Avatar>
                            </Link>
                        </Box>
                    </Box>
                </Grid>
            </Grid>
        </>
    )
}

export async function getServerSideProps(context) {
    const idUsuario = context.params.idUsuario;

    const res = await fetch(
        `${process.env.INDICADORES_BASE_URL}/usuarios/${idUsuario}/profile`
    );

    const data = await res.json();
    if (res.status === 200) {
        return {
            props: { ...data },
        };
    } else {
        return {
            props: {
                data: [],
            }
        }
    }
}

Now, I want to be able to use the “ownerID” into the fetching in order to retrieve my user, but, is this possible or is this the correct approach?

Routingissu, indexpage keeps showing in other pages

So I am trying to get to know angular, but I have a routing issue. I have made a simple app that on the index page shows a title and than a list, when you hover over them you see the photo in detail. These are pictures of dogs or fruits. Than I made two links, one going to a page with exactly the same list, but only fruits. Another links goes to page with the list of dog pictures. The problem I have is that when I go to the list of dogs/fruits- only, the index page also shows up their again. I do not understand how this happens and how I can resolve it. Here below my code(I left css out, only took html and component) (I also left the detail app out since it works just fine):

app-component

import { Component, OnInit } from '@angular/core';
import { Foto } from './model/Foto';
import { FotoService } from './foto.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Yannick's taak';
  fotos!: Foto[];
  selectedFoto!:Foto;


  onHover(foto:Foto): void {
    this.selectedFoto = foto;
  }

  constructor(private fotoService: FotoService){}

  ngOnInit(): void {
    this.fotoService.getFotos().subscribe(fotos=>this.fotos=fotos);
  }

}

app.component.html

<title>{{title}}</title>
<h1>{{title}}</h1>


<nav>
<a routerLink="/fruitfotos">Foto's fruit</a>
<a routerLink="/hondenfotos">Foto's honden</a>
</nav>
<router-outlet></router-outlet>

<h1>alle foto's:</h1>

<ul>
  <li *ngFor="let foto of fotos" (mouseover)="onHover(foto)" [style.backgroundColor]="foto.id%2===0?'red':'green'">{{foto.name}}</li>
</ul>


<app-foto-details [foto]="selectedFoto"></app-foto-details>

routing-module

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FruitFotosComponent } from './fruit-fotos/fruit-fotos.component';
import { HondenFotosComponent } from './honden-fotos/honden-fotos.component';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(
    [
      {path:"fruitfotos",
    component: FruitFotosComponent},
      {path:"hondenfotos",
  component: HondenFotosComponent}
    ]
  )],
  exports: [RouterModule]
})
export class AppRoutingModule { }

fotoService:

import { Injectable } from '@angular/core';
import { Foto } from './model/Foto';
import { FOTOS } from './mock-fotos';
import { Observable, of } from 'rxjs';

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

  getFotos(): Observable<Foto[]> {
      return of(FOTOS);
  }

  getFruitFotos(): Observable<Foto[]> {
    return of(FOTOS.filter(foto=>foto.type=="fruit"));
  }

  getHondFotos(): Observable<Foto[]> {
    return of(FOTOS.filter(foto=>foto.type=="honden"));
  }


  constructor() { }
}

fruit foto component:

import { Component, OnInit } from '@angular/core';
import { FotoService } from '../foto.service';
import { Foto } from '../model/Foto';

@Component({
  selector: 'app-fruit-fotos',
  templateUrl: './fruit-fotos.component.html',
  styleUrls: ['./fruit-fotos.component.css']
})
export class FruitFotosComponent implements OnInit {
  fotos!: Foto[];
  selectedFoto!:Foto;


  onHover(foto:Foto): void {
    this.selectedFoto = foto;
  }

  constructor(private fotoService:FotoService) { }

  ngOnInit(): void {
    this.fotoService.getFruitFotos().subscribe(fruitfotos=>this.fotos=fruitfotos);
  }

}

fruit fotos html

<h1>Fruitfoto's</h1>
<ul>
    <li *ngFor="let foto of fotos" (mouseover)="onHover(foto)" [style.backgroundColor]="foto.id%2===0?'red':'green'">{{foto.name}}</li>
  </ul>
  
  
 <app-foto-details [foto]="selectedFoto"></app-foto-details>

dog foto component:

import { Component, OnInit } from '@angular/core';
import { Foto } from '../model/Foto';
import { FotoService } from '../foto.service';

@Component({
  selector: 'app-honden-fotos',
  templateUrl: './honden-fotos.component.html',
  styleUrls: ['./honden-fotos.component.css']
})
export class HondenFotosComponent implements OnInit {
  fotos!: Foto[];
  selectedFoto!:Foto;


  onHover(foto:Foto): void {
    this.selectedFoto = foto;
  }

  constructor(private fotoService:FotoService) { }

  ngOnInit(): void {
    this.fotoService.getHondFotos().subscribe(hondenfoto=>this.fotos=hondenfoto);
  }

}

dog fotos html:

<h1>Hondenfoto's</h1>
<ul>
    <li *ngFor="let foto of fotos" (mouseover)="onHover(foto)" [style.backgroundColor]="foto.id%2===0?'red':'green'">{{foto.name}}</li>
  </ul>
  
  
 <app-foto-details [foto]="selectedFoto"></app-foto-details>

Let me know if you need other component but I guess this should do ?