how to stop getting # in href? html javascript

i am trying to access a php page with this anchor tag:

<li>
                            <a href="test.php">
                                <i data-feather="home"></i>
                                <span data-key="t-settings">Settings</span>
                            </a>
                        </li>

Ideally this link must open the below URL:

https://example.com/test.php

but what happening is whenever i click that link i get :

 https://example.com/#test.php

an extra hash in my url due to which i am not able to access the page ?

any solutions?
Thanks in advance <3

Upload and retrieve post image with summernote

I’m trying to upload and retrieve summernote in admin/includes/scripts.php:

$('#summernote').summernote({
                 height: 200,
                 callbacks: {
                         onImageUpload: function(files, editor, welEditable) {
                                 sendFile(files[0], editor, welEditable);
                         }
                 }
         });

         function uploadImage(image) {
                 var data = new FormData();
                 data.append("image", image);
                 $.ajax({
                         url: '../uploads/posts/',
                         cache: false,
                         contentType: false,
                         processData: false,
                         data: data,
                         type: "post",
                         success: function(url) {
                                 var image = $('<img>').attr('src', 'http://' + url);
                                 $('#summernote').summernote("summernote_upload.php", image[0]);
                         },
                         error: function(data) {
                                 console.log(data);
                         }
                 });
         }

to uploads/posts image folder with admin/summernote_upload.php:

<?php
include('config/dbconn.php');

if (isset($_FILES['file']['name'])) {
    if (!$_FILES['file']['error']) {
        $name = rand(100,1000).'_'.date('Ymd');
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $filename = $name.'.'.$ext;
        $destination = '../uploads/posts/'.$filename;
        $location = $_FILES["file"]["tmp_name"];
        move_uploaded_file($location, $destination);
        echo '../uploads/posts/'.$filename;
    } else {
        echo 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
    }
}

and post-edit.php:

<div class="col-md-12 mb-3">
    <label for="">Description</label>
    <textarea name="description" id="summernote" required class="form-control" rows="4"><?= htmlentities($post_row['description']) ?></textarea>
</div>

I’m not sure, if I’ve correctly used the code above and if it does not contains mistakes, in addition here is a Chrome console, I’m not quite understand, how to figure out with this^

jquery-3.6.0.min.js:2064 jQuery.Deferred exception: sendFile is not
defined ReferenceError: sendFile is not defined
at HTMLTextAreaElement.onImageUpload (http://localhost/lado/php-blog/admin/post-edit.php?id=6:350:34)
at t.value (https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.js:2:20981)
at t.value (https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.js:2:62950)
at t.value (https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.js:2:22382)
at https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.js:2:119668
at e (http://localhost/user/blog/admin/js/jquery-3.6.0.min.js:1956:36)
at t (http://localhost/user/blog/admin/js/jquery-3.6.0.min.js:1980:29)
undefined

Parsing error: “,” expected on conditional return

I really can get why, when I add a slice method to this function, i get a parsing error that needs a comma. Syntax looks correct to me. Any idea?

    const getObjectKeys = (object: any) => {
        Objeckt.keys(object).reduce((prevValue, value) => {
            if (value.startsWith("bo-")) {
                return { ...prevValue, value }
            } else {
                return { ...prevValue, value.slice(3) }
            }
        }, {})
    }

React Get request with list as parameter

I need to send an array list with one element as params to service with get method on the frontend I wrote something like

var list = [id]

And called API as

method : 'get',
data: {
  idlist:list
}

I also tried

idlist: list.join(',')
idlist: encodeURIComponent(list)

In example URL call there is nothing as []

So when I use as first one it calls as

idlist[] =

In second one

idlist=some number but not working

If I use JSON.stringfy
idlist=[some number but still not working]
At this point I don’t know what I should try. Also I’m sorry if I couldn’t explain my problem I’m very bad at explaining.

JS finding extreme values in json

I need to find extreme values in json with given average number but honestly I have no idea how to approach to this problem.
so I have json with values like that:

const avg = 0.5;
const myjson = {
 'key1': 0.5,
 'key2': 0.8,
 'key3': 0.3,
 'key4': 0.2,
 'key5': 0.5,
};

So basically average is 0.5, and I wish to get biggest extremes, in above example it would be ‘key2’ and ‘key4’.

so the output should look like this:

const reducedJson = {
 'key2': 0.8,
 'key4': 0.2,
}

Also in case if there is 3 exteme values, for example there would be ‘key6’: 0.2, I should return three extremes because two are same.

Sorry that no my code but as I said, I need some help or tip at least because I don’t know how to start…
Thanks

How should you pass the tooltip title to an svg icon to give it an accessible title in MUI?

When using a tooltip around an icon button the button automatically will get the a11y name of the tooltip title. The example from the docs makes it so a screen reader reads it as “Delete, button” which is good.

<Tooltip title="Delete">
  <IconButton>
    <DeleteIcon />
  </IconButton>
</Tooltip>

But trying to do the same thing when simply using an svg icon does not work.

Instead having just

<Tooltip title="Delete">
  <DeleteIcon />
</Tooltip>

Makes it so the image is inaccessible due to how MUI default handles a11y for SvgIcons. So what I can do is simply passing the tooltip title to the titleAccess prop of the icon.

const title = "Delete";

<Tooltip title={title}>
  <DeleteIcon titleAccess={title}/>
</Tooltip>

Which works fine. The tooltip works on hover and a screen reader can access it and reads it as “Delete, image”. Is this the way how this is supposed to be done though? Or is it possible for the icon to pickup the title from the tooltip directly so the title does not need to be set twice?

The use case I have for this is to show an icon that explains stock status of an item. So it is supposed to be non interactive but possible for users to get a text explanation if they don’t understand the icon.

Here is a codesandbox with the different examples running:
https://codesandbox.io/s/mui-icon-tooltip-a11y-9smgoc?file=/src/App.tsx

How do I pass the id from the addNewFriendClick to my onClickUpdate?

I have a friend form that has a button to add friend via ajax call (addNewFriendClick). Once added it should output the id and then using that id the same button (onClickUpdate) should allow to update by grabbing that id.
After adding and clicking a second time to update the friend I get the error below in my console.

The website below should have the /id as the url ending endpoint but i am getting
“[object%20Object]”

PUT https://api.remotebootcamp.dev/api/friends/[object%20Object] 404 (Not Found)

import React, { useState, useEffect } from "react";
import * as friendService from "../../services/friendService";
import toastr from "toastr";
import { useParams, useNavigate, useLocation } from "react-router-dom";

function AddFriend() {
  const [userFormData, setUserFormData] = useState({
    title: "",
    bio: "",
    summary: "",
    headline: "",
    slug: "",
    statusId: "",
    primaryImage: "",
  });
  // useEffect to grab url

  const navigate = useNavigate();
  const { state } = useLocation();
  const friendId = useParams();

  const [peepId, setPeepId] = useState(friendId);
  console.log({ userFormData, peepId, state }, "param and navigate");
  useEffect(() => {
    console.log("useEffect firing");
    setPeepId(friendId);
    if (state) {
      setUserFormData((prevState) => {
        console.log(state);
        return { ...prevState, ...state.payload };
      });
    }
  }, [friendId, state]);

  const onFormFieldChange = (event) => {
    const target = event.target;
    const value = target.value;
    console.log("VALUE ->", value);
    const name = target.name;
    console.log("NAME ->", name);

    setUserFormData((prevState) => {
      console.log("updater onChange");
      const updatedFormData = {
        ...prevState,
      };

      updatedFormData[name] = value;

      return updatedFormData;
    });
  };

  useEffect(() => {
    console.log("useEffect firing");
    setPeepId(friendId);
    if (state) {
      setUserFormData((prevState) => {
        console.log(state);
        return { ...prevState, ...state.payload };
      });
    }
  }, [friendId, state]);

  const addNewFriendClick = (event) => {
    event.preventDefault();
    console.log(userFormData, "inside addNewFriendClick")
    console.log("on Click", { syntheticEvent: event });
    friendService.addFriend(userFormData).then(onSuccessAdd).catch(onErrAdd);
  };

  const onSuccessAdd = (response) => {
    console.log(response, "onSuccessAdd response");
    // console.log(response.data.item, "onSuccessAdd response.data.item");

    setNewFriendInformation(response);
    console.log(response,"onSuccessAdd after setNewFriend" )
    friendService.getFriendById(response).then(onSuccessGet).catch(onErrorGet);
    toastr.success("Congratulations! You have successfully added a friend!");
  };

  const onErrAdd = (err) => {
    console.log("ping err", err);
    // swal("Error Registering");
    toastr.error(
      "Error adding a new friend. Please check if all fields are correct"
    );
  };

  const onClickUpdate = (event) => {
    console.log(userFormData, "userFormData inside click Edit");
    event.preventDefault();
    friendService
      .updateFriend(userFormData)
      .then(onSuccessUpdate)
      .catch(onErrorUpdate);
  };

  const onSuccessUpdate = (response) => {
    console.log(response);
    toastr.success("Congratulations! You have successfully updated a friend!");
    navigate("/friends");
  };
  const onErrorUpdate = (error) => {
    console.log(error, "inside error update");
    toastr.error(
      "Error updating friend. Please check all fields are correct and that user being updated is valid"
    );
  };

  const setNewFriendInformation = (id) => {
    setUserFormData((prevState) => {
      let newState = { ...prevState };
      newState.id = id;

      return newState;
    });
  };

  const onSuccessGet = (response) => {
    console.log(response);

    navigate();
  };
  const onErrorGet = (error) => {
    console.log(error);
    console.log("inside getById error form");
  };
  // const updateFriend()
  return (
    <React.Fragment>
      <h1 className="container">Add New</h1>
      <hr />
      <main role="main">
        <div className="container col-6 mt-5 fs-2">
          <div className="row">
            <div className="col-md-5">
              <form>
                <div className="mb-3">
                  <label htmlFor="title" className="form-label">
                    Title
                  </label>
                  <input
                    type="text"
                    className="form-control  form-control-lg"
                    id="title"
                    name="title"
                    placeholder="Please The Enter Title"
                    onChange={onFormFieldChange}
                    value={userFormData.title}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="bio" className="form-label">
                    Bio
                  </label>
                  <input
                    type="text"
                    className="form-control  form-control-lg"
                    id="bio"
                    name="bio"
                    placeholder="Please Enter The Bio"
                    value={userFormData.bio}
                    onChange={onFormFieldChange}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="summary" className="form-label">
                    Summary
                  </label>
                  <input
                    type="text"
                    className="form-control  form-control-lg"
                    id="summary"
                    name="summary"
                    placeholder="Please Enter The Summary"
                    onChange={onFormFieldChange}
                    value={userFormData.summary}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="headline" className="form-label">
                    Headline
                  </label>
                  <input
                    type="text"
                    className="form-control  form-control-lg"
                    id="headline"
                    name="headline"
                    placeholder="Please Enter The Headline"
                    onChange={onFormFieldChange}
                    value={userFormData.headline}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="slug" className="form-label">
                    Slug
                  </label>
                  <input
                    type="text"
                    className="form-control  form-control-lg"
                    id="slug"
                    name="slug"
                    placeholder="Please The Slug"
                    onChange={onFormFieldChange}
                    value={userFormData.slug}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="statusId" className="form-label">
                    Status Id
                  </label>
                  <select
                    type="select"
                    className="form-control"
                    id="statusId"
                    name="statusId"
                    placeholder="Please Enter Status ID"
                    onChange={onFormFieldChange}
                    value={userFormData.statusId}
                  >
                    <option>Default</option>
                    <option value="Active">Active</option>
                    <option value="NotSet">NotSet</option>
                    <option value="Deleted">Deleted</option>
                    <option value="Flagged">Flagged</option>
                  </select>
                </div>
                <div className="mb-3">
                  <label htmlFor="primaryImage" className="form-label">
                    Primary Image Url
                  </label>
                  <input
                    type="text"
                    className="form-control  form-control-lg"
                    id="primaryImage"
                    name="primaryImage"
                    placeholder="Please Enter The Primary Image"
                    onChange={onFormFieldChange}
                    value={userFormData.primaryImage}
                  />
                </div>
                {userFormData.id ? (
                  <button
                    onClick={onClickUpdate}
                    type="sumbit"
                    className="btn btn-primary"
                  >
                    Update Friend
                  </button>
                ) : (
                  <button
                    onClick={addNewFriendClick}
                    type="sumbit"
                    className="btn btn-primary"
                  >
                    Add Friend
                  </button>
                )}
              </form>
            </div>
          </div>
        </div>
        <div className="col-md-5">
          <h5>Output</h5>
          <pre>
            <code>{JSON.stringify(userFormData, undefined, 2)}</code>
          </pre>
        </div>
      </main>
    </React.Fragment>
  );
}

export default AddFriend;

import axios from "axios";
import * as helper from "./serviceHelper";

let getFriend = () => {
  const config = {
    method: "GET",
    url: "https://api.remotebootcamp.dev/api/friends?pageIndex=0&pageSize=10",
    withCredentials: true,
    crossdomain: true,
    headers: { "Content-Type": "application/json" },
  };
  return axios(config).then(helper.onGlobalSuccess);
  //we use data as the param for success handler
};

let addFriend = (payload) => {
  const config = {
    method: "POST",
    url: "https://api.remotebootcamp.dev/api/friends",
    data: payload,
    withCredentials: true,
    crossdomain: true,
    headers: { "Content-Type": "application/json" },
  };
  return axios(config).then(response => {
    console.log(response, "inside service addfriend return")
    return response.data.item;
});
}

let updateFriend = (id, payload) => {
  console.log(id, payload, "from updateFriendservice");
  const config = {
    method: "PUT",
    data: (id, payload),
    url: `https://api.remotebootcamp.dev/api/friends/${id}`,
    withCredentials: true,
    crossdomain: true,
    headers: { "Content-Type": "application/json" },
  };
  return axios(config);
};

let deleteFriend = (id) => {
  console.log(id);
  const config = {
    method: "DELETE",
    // data: id,
    url: `https://api.remotebootcamp.dev/api/friends/${id}`,
    withCredentials: true,
    crossdomain: true,
    headers: { "Content-Type": "application/json" },
  };
  return axios(config);
};

let getFriendById = (id, payload) =>{
  console.log(id, payload, "inside getFriend friedService")
  const config = {
    method: "PUT",
    data: (id, payload),
    url: `https://api.remotebootcamp.dev/api/friends/${id}`,
    withCredentials: true,
    crossdomain: true,
    headers: { "Content-Type": "application/json" },
  }
  return axios(config);
}
export { getFriend, addFriend, deleteFriend, updateFriend, getFriendById };

React useEffect delayed only with file upload

My file upload feature involves two components, ViewProjectAttachment to view list of attachments related to the project and AddAttachment, a form for uploading files.

ViewProjectAttachment.js

import React, {useEffect, useState, useContext} from 'react'
import Axios from 'axios';
import {Col, Row, Button, Modal, Table, Form} from 'react-bootstrap';
import {Image} from 'cloudinary-react';
import { UserContext, UserTypeContext } from './../Helper/Context';
import { useHistory } from 'react-router-dom';


function ViewProjectAttachment({itemID, isBelong}) {

    var projectId = itemID;

    const {userId, setUserId} = useContext(UserContext);
    const {type, isUserType} = useContext(UserTypeContext);

    const history = useHistory();

    const [attachmentList, setAttachmentList] = useState([]);

    const [fileSelected, setFile] = useState();

    const [showModal, setShowModal] = useState(false);
    const handleClose = () => setShowModal(false);

    const [delAttachment, setDelAttachment] = useState (false);
    const handleDelete2 = () => setDelAttachment(false);

    useEffect(()=>{
        
        Axios.get(`http://localhost:3001/${projectId}/attachment`,{
            projectId: projectId,
        })
        .then((response) => {
            
            setAttachmentList(response.data);
            
        })
    },[attachmentList]);

    const addNewAtt = () => {
        if(type === 'Staff'){
            history.push(`/staff/${userId}/addattachment/${projectId}`);
        }
        else if(type === 'Student'){
            history.push(`/student/${userId}/addattachment/${projectId}`);
        }
    }

    const deleteAttachment = (e, attachment_id) => {

        e.preventDefault();

        const attachmentId = attachment_id;

        Axios.delete(`http://localhost:3001/delattachment/${attachmentId}`, {
            attachmentId: attachmentId,
        })
        .then((respon) => {
            
            handleDelete2();
            window.alert("Attachment has been deleted!");
            
         })
    }

  return (
    <div>
            <Row>
                <Col className = "d-flex justify-content-start fw-bold">
                    Attachment
                </Col>
                <Col className = "d-flex justify-content-end">
                    <Button variant="link" onClick={addNewAtt}>+ Add</Button>
                </Col>
            <hr/>
            </Row>
            <Form>
                            
                            <Form.Group className="mb-3" controlId="image">

                                <Form.Control type="file"
                                    onChange={(event) => {
                                        setFile(event.target.files[0]);
                                    }}
                                />
                            </Form.Group>

                            
                            <div className = "d-flex flex-end justify-content-end align-items-end mt-3">
                                <div>
                                    <Button onClick={uploadImage}>Save</Button>
                                </div>
                            </div>
                        </Form>
                </Row>

                    <Modal show={showModal} onHide={handleClose}>
                        <Modal.Header closeButton>
                        <Modal.Title>SUCCESSFUL</Modal.Title>
                        </Modal.Header>
                        <Modal.Body>You have successfully uploaded an image!</Modal.Body>
                        <Modal.Footer>
                        <Button variant="secondary" onClick={handleClose}>
                            Close
                        </Button>
                        </Modal.Footer>
        
    </div>
  )
}

export default ViewProjectAttachment

AddAttachment.js

import React, {useState, useContext} from 'react'
import {Form, Button, Card} from 'react-bootstrap'
import Axios from 'axios';
import { useHistory } from 'react-router-dom';
import { UserContext, UserTypeContext } from './../Helper/Context';

function AddAttachment() {

    const history = useHistory();

    const {userId, setUserId} = useContext(UserContext);
    const {type, isUserType} = useContext(UserTypeContext);

    const link = window.location.pathname;
    const split = link.split("/");
    const projectId = split[4];

    const [file, setFile] = useState();
    const [fileName, setFileName] = useState("");
 
      const saveFile = (event) => {

        event.preventDefault();
        setFile(event.target.files[0]);
        setFileName(event.target.files[0].name);
      };
 
      const uploadFile = async(e, projectId) => {

        e.preventDefault();

        const formData = new FormData();
        formData.append("file", file);
        formData.append("fileName", fileName);
        formData.append("projectId", projectId);
        try {
          const res = await Axios.post(
            "http://localhost:3001/uplatt",
            formData,
          ).then((res) => {
            if(res.data.successfulAdd){

                if(type === 'Staff'){
                    window.alert('You have successfully uploaded an attachment!');
                    history.push(`/staff/${userId}/viewproject/${projectId}`);
                }
                else if(type === 'Student'){
                    window.alert('You have successfully uploaded an attachment!');
                    history.push(`/student/${userId}/viewproject/${projectId}`);
             }
            }
          });


        } catch (ex) {
          console.log(ex);
        }


      };

    const backToProject = (e) => {
        e.preventDefault();

        if(type === 'Staff'){
            history.push(`/staff/${userId}/viewproject/${projectId}`);
        }
        else if(type === 'Student'){
            history.push(`/student/${userId}/viewproject/${projectId}`);
        }
    }

  return (
    <div className="d-flex justify-content-center">
            <Card style={{ width: '70%' }}>
            <div className = "mt-3 p-5">
                <h3>
                    Add new attachment
                </h3>
                <hr/>
                <Form onSubmit={(event) => uploadFile (event, projectId)}>
                <div className="mt-1 mb-3">
                    <input type="file" name="file" onChange={(e) => saveFile(e)} />
                </div>
                <div className = "d-flex flex-end justify-content-end align-items-end mt-3">
                    <div className = "px-3">
                    <Button type="button" style={{color:'white', backgroundColor:'#104271'}} onClick={backToProject} className = "mr-3">Cancel</Button>
                    </div>
                    <div>
                    <Button type="submit" style={{color:'white', backgroundColor:'#104271'}}>Upload</Button>
                    </div>
                </div>
                </Form>
            </div>
            </Card>
        </div>
  )
}

export default AddAttachment

Problem is, the attachmentList is not updated right after the file has been saved to database and server public folder. It took a few seconds to show, eventhough I have already added attachmentList as a dependency array in my useEffect. My back-end code:

app.get("/:projectId/attachment", function(req, res){

    const projectId = req.params.projectId;

    try{
        const findProjectAttachment = "SELECT project_attachment.project_attachment_id, project_attachment.project_attachment_url, project_attachment.project_id FROM project_attachment INNER JOIN project ON project_attachment.project_id=project.project_id WHERE project_attachment.project_id = ?;";

        db.query(findProjectAttachment, projectId, (err, result) => {

            if(result.length > 0){
                res.send(result);
            }
        }
        )
    }
    catch(err){
        console.log(err);
    }
});

This is also only happening with my upload feature. The others work just fine. Anyone?

Angular route, different behaviour based on logged in status

Maybe not the best approach, but I want to use the same Angular path for both logged in and unauthenticated users to display a component. I have a skeleton component which contains the components after the user has logged in. If the user isnt logged in I dont want to display the skeleton component only the component itself.

routing:

{
    path: '',
    component: SkeletonComponent,
    canActivate: [AuthGuardService],
    children: [
      {
        path: 'dashboard',
        loadChildren: () =>
          import('./dashboard/dashboard.module').then((m) => m.DashboardModule),
      },
      {
        path: 'opti-inspector',
        loadChildren: () =>
          import('./opti-inspector/opti-inspector.module').then(
            (m) => m.OptiInspectorModule
          ),
      },
      {
        path: '**',
        component: PageNotFoundComponent,
      },
    ],
  },

I want to introduce a protocol component, which is avaialable as both the child of the SkeletonComponent if the user is logged in, or a separate path if the user is not logged in.
How could I achieve this?

Unsuccesful trial:

{
    path: '',
    component: SkeletonComponent,
    canActivate: [AuthGuardService],
    children: [
      {
        path: 'dashboard',
        loadChildren: () =>
          import('./dashboard/dashboard.module').then((m) => m.DashboardModule),
      },
      {
        path: 'opti-inspector',
        loadChildren: () =>
          import('./opti-inspector/opti-inspector.module').then(
            (m) => m.OptiInspectorModule
          ),
      },
      {
        path: 'protocol',
        loadChildren: () =>
          import('./protocoll/protocoll.module').then((m) => m.ProtocollModule),
      },
      {
        path: '**',
        component: PageNotFoundComponent,
      },
    ],
  },
  {
    path: 'protocol',
    loadChildren: () =>
      import('./protocoll/protocoll.module').then((m) => m.ProtocollModule),
  },

Format json object with keys in api payload

During an api call I am sending a json object to save data and when I see in the network payload I can see the json object keys are reordered according to alphabetical order. Is there any way to change this behaviour so that I can send json object in the payload with the keys ordered according to my need.

Import Javascript modules in Yeoman Excel add-in project

I’m trying to create an Excel add-in with Yeoman generator. In the excel_project/src/taskpane/taskpane.js file I’d like to call the ‘fs‘ library. When I execute taskpane.js alone on my terminal, everything works fine. However, when I launch the whole Excel project (npm start on my terminal) I have a module import error (see image). It’s as if modules couldn’t be imported in the Excel add-in… Does anyone have any ideas ?
Thanks for your help.

Here is the taskpane.js file, like it is created by Yeoman. I’ve just added const fs = require('fs'); // this gives the error

Office.onReady((info) => {
  if (info.host === Office.HostType.Excel) {
    document.getElementById("sideload-msg").style.display = "none";
    document.getElementById("app-body").style.display = "flex";
    document.getElementById("run").onclick = run;
  }
});

export async function run() {
  try {

    const fs = require('fs'); // this gives the error

    
    await Excel.run(async (context) => {

      const range = context.workbook.getSelectedRange();
      let text = document.querySelector('textarea').value;

      // Read the range address
      range.load("address");

      // Update the fill color
      range.format.fill.color = "yellow";

      await context.sync();
      console.log(`The range address was ${range.address}.`);
    });
  } catch (error) {
    console.error(error);
  }

}

result appearing twice in calculator

hi everyone i am jonnathan i am trying to create a calculator in javascript and i am following a tutorial on youtube but for some reason if i add 1 and 1 together the result 2 is alerting twice there are no errors in the console either that i think could help me with this issue

var number1 = prompt("Input the first number");
var op = prompt("Input operator")
var number2 = prompt("Input 3rd number")

if (op == "+") {
    if (number1 == "1")
    {
        if (number2 == "1")
        {
            alert("2");
        }
        if (number2 == "2")
        {
            alert("3");
        }
        if (number2 == "3")
        {
            alert("4");
        }
        if (number2 == "4")
        {
            alert("5");
        }
        if (number2 == "5")
        {
            alert("6");
        }
        if (number2 == "6")
        {
            alert("7");
        }
        if (number2 == "7")
        {
            alert("8");
        }
        if (number2 == "8")
        {
            alert("9");
        }
        if (number2 == "9")
        {
            alert("10");
        }
    }
    if (number2 == "1")
    {
        if (number1 == "1")
        {
            alert("2");
        }
        if (number1 == "2")
        {
            alert("3");
        }
        if (number1 == "3")
        {
            alert("4");
        }
        if (number1 == "4")
        {
            alert("5");
        }
        if (number1 == "5")
        {
            alert("6");
        }
        if (number1 == "6")
        {
            alert("7");
        }
        if (number1 == "7")
        {
            alert("8");
        }
        if (number1 == "8")
        {
            alert("9");
        }
        if (number1 == "9")
        {
            alert("10");
        }
    }
}

so far the calculator only adds numbers and only does it through 1 ti 9. how can i fix this error?

what these functions are doing in javascript?

*javascript
I am new to javascript and I am struggling to understand the functionality of this code .I wanted to return some values as a part of my assignment.

var _createClass = function ()
{
function defineProperties(target, props)
{
for (var i = 0; i < props.length; i++)
{
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if (“value” in descriptor)
descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps)
{ if (protoProps)
defineProperties(Constructor.prototype, protoProps);
if (staticProps)
defineProperties(Constructor, staticProps); return Constructor;
};
}();enter code here