Async function Javascript [duplicate]

const res = async function () {
  return await Fruit.updateOne(
    { _id: "646eeadd735547c9433ec97a" },
    { name: "Peach", Rating: 5 }
  );
};

const res1 = res();

I want to wait until my async function gets executed but the res1 is running in an async way

How to show Initial content of Bootstrap Modal

I am showing bootstrap modal using below code.

        $(document).ready(function(){
            $("#plan_templates").click(function() {
                $('.modal').find('.modal-content').html($('.modal-content').eq(0).html());
                $(".modal").modal("show");

                $(".tplan").click(function() {
                    var index = $(".tplan").index(this);
                    $('.modal').find('.modal-content').html($('.tab').eq(index).html());
                });
            });
        });

I would like to show content of $('.modal').find('.modal-content').html($('.modal-content').eq(0).html()); on modal at initial stage always when click on "#plan_templates" button.

But I am getting content of $('.modal').find('.modal-content').html($('.modal-content').eq(0).html()); on modal at first time when I click on "#plan_templates" button. I am getting content of $('.modal').find('.modal-content').html($('.tab').eq(index).html()); on modal at second time.

How to avoid endless render loop in React while updating Parent Accordion height?

Hi everyone and thanks for reading. I have a big problem in React with a nested Accordion. In fact when the child Accordion opens, the parent Accordion was not updating.

interface AccordionProps {
  title?: string;
  subtitle?: string;
  children: React.ReactNode;
  isOpened?: boolean;
  topChildren?: React.ReactNode;
  bottomChildren?: React.ReactNode;
  onToggle?: () => void;
}

function Accordion({
  title,
  subtitle,
  children,
  isOpened = false,
  topChildren,
  bottomChildren,
  onToggle,
}: AccordionProps) {
  const [open, setOpen] = useState(isOpened);
  const contentRef = useRef<HTMLDivElement>(null);
  const [contentHeight, setContentHeight] = useState("0px");

  useEffect(() => {
    if (contentRef.current && contentRef.current.parentElement) {
      setContentHeight(open ? `${contentRef.current.scrollHeight}px` : "0px");
    }
    if (onToggle) {
      onToggle();
    }
  }, [contentRef, open, children, onToggle]);

  return (
    <div className={styles.accordion}>
      <div className={styles.top} onClick={() => setOpen(!open)}>
        <div className={styles.left}>
          {topChildren || (
            <>
              <div className={styles.title}>{title}</div>
              <div className={styles.subtitle}>{subtitle}</div>
            </>
          )}
        </div>
        <div className={styles.right}>
          <img
            src={iconArrowDown}
            alt=""
            className={`${styles.arrowIcon} ${
              open ? styles.arrowIconRotated : ""
            }`}
          />
        </div>
      </div>
      <div
        ref={contentRef}
        className={`${styles.content} ${open ? styles.open : ""}`}
        style={{
          maxHeight: contentHeight,
        }}
      >
        <div className={styles.overflow}>{children}</div>
        {bottomChildren && <div>{bottomChildren}</div>}
      </div>
    </div>
  );
}

export default Accordion;

HomePage

function HomePage() {
  return (
    <div>
     
        <ParentAccordion />
    </div>
  );
}

export default HomePage;

function ParentAccordion() {
  const [update, setUpdate] = useState(0);

  const handleToggle = () => {
    setUpdate((prevUpdate) => prevUpdate + 1);
  };

  return (
    <Accordion title="Parent" onToggle={handleToggle}>
     Lorem Ipsum is simply dummy text of the printing 
      <Accordion title="Child">
        <div
          style={{
            width: "300px",
            height: "300px",
            backgroundColor: "yellowgreen",
          }}
        >
        Lorem Ipsum is simply dummy text of the printing
        </div>
      </Accordion>
    </Accordion>
  );
}

Thank you very much, you save my life

So I passed a callBackyour text function onToggle. To be able to determine the opening of the child Accordion and update the Parent. it works but i have a problem of endless rendering loop. I can’t seem to keep the behavior that causes the height of the Parent to update when the child opens without getting the error:

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn’t have a dependency array, or one of the dependencies changes on every render.

How to open the webcam screen on the personal homepage of an ip other than localhost

I was working on a project, and the webcam on localhost was strange, so I proceeded with the project, but the webcam screen was not output because I used a different ip than the localhost for communication with spring and react. So I searched for the cause, and it came out that it was not https, but security was not guaranteed.

First of all, I went through the aws domain, ec2 instance, and ssl certificate issuance, but I don’t know what to do next.
And my environment is windows and I am using intellij.

How does HTML recognize function?

just got question about how does HTML works.

As far as I know, attribute of HTMLElement is only ‘string | null’

but as we know, on HTML


<div onclick="sayHi()" />

works.

I’m wondering, how does ‘sayHi’ string gets map into actual function object.

and in advance, for web components, can we pass functions to web-component attributes? not using global object as proxy?

Trying to use value in number field1 to display in readonly div2

I’m converting a Google Sheets that collects several data inputs from the user and then does a lot of calculations. I know have to convert it to a webpage and tie it to an SQL database.

I’m using jquery to manipulate the calculable data on the web page, and I’m good with the SQL.

I’ve worked with Javascript years ago and am a little rusty. I just need a little jump start.

I have created a table of 5 rows that captures the square feet (SF) of three space types.

Space Type is a drop-down
Floor Area is an with type = number.
% Area is calculated (Floor Area รท Total Area)

The rest are DIVs and the calculation will show in their respective column,.

% Area will calulate the repsetive spaces floor area are show in that row’s cell.

kWh Used will use a value associated with a Space Type and multiply that by the Floor Area, e.g. Office = 21 kWh x 20,000 SF will show 420,000 kWh uused in the cell under kWh Used in row 1.

I’ve used document.getElementById() in the past, however the syntax is a bit different with jquery. I’m good with reference material that shows examples. So if someone knows of a online soycers please point me to it and I should be able to work my way through this.

My question is, how do I capture the text in Space Type and Floor Area and show the results of the %Area? If I can understgand. that I can probably figure the rest out.

-----------+------------+--------+----------+----------
Space Type | Floor Area | % Area | kWh Used | kWh Cost 
-----------+------------+--------+----------+----------
Office     |  20,000    |   12%  |   50,000 |  $5,000
-----------+------------+--------+----------+----------
Hotel      |  150,000   |   87%  |  120,000 | $12,000
-----------+------------+--------+----------+----------
Retail     |  2,000     |    1%  |   19,000 |  $1,900
-----------+------------+--------+----------+----------
Total                   |  100%  |  241,000 | $18,900
-----------+------------+--------+----------+----------


Copy paste Functionality in React input field with Skipping acording to Excel copied Record

I am trying to perform copy paste functionality.

Copy the data from the excel file and Paste the record in the input field. I should be able to paste according to the respective fields. If I Copied 3*3 matrix cell from the excel and pasted the data into the 5th input field 5th 6th input should be and should skip the 7th field. continue 8th 9th similar.

I am facing problem with skipping the input field.

Code:

import React, {useState} from 'react';

const MultipleInputFields = () => {
    const [inputValues,
        setInputValues] = useState([
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        ""
    ]);

    const handleInputChange = (e) => {
        const {value} = e.target;
        const updatedValues = [...inputValues];
        updatedValues[
            e
                .target
                .getAttribute("attr")
        ] = value;
        setInputValues(updatedValues);
    };

    const handlePaste = (event) => {

        let pastedData = event
            .clipboardData
            .getData('text/plain');

        pastedData = pastedData.substring(0, pastedData.length - 1);

        const rows = pastedData.split('n');

        const horizontalValues = [];
        const verticalValues = [];
        const updatedValues = [...inputValues];

        var attribute = parseInt(event.target.getAttribute("attr"));
        var verticalIndex = attribute;
        var horizontalIndex = attribute;
        rows.forEach((row, indexValue) => {
            const values = row
                .split('t')
                .map((value) => value.trim());

            if (values.length == 1) {
                for (verticalIndex; verticalIndex <= updatedValues.length;) {
                    updatedValues[verticalIndex - 1] = values[0]
                        ?.trim();
                    verticalIndex = verticalIndex + 3
                    break;
                }
            }
            if (values.length > 1) {
                var index = 0,
                    indexData = 0;
                for (var i = attribute + indexValue; i <= updatedValues.length; i++) {

                    if (index >= values.length || ((indexData == 0) && ((attribute) % 3 === 2 && attribute / 3 < 12))) {
                        //     horizontalIndex = horizontalIndex + 3 - values.length;
                        if (values.length == 2) {
                            horizontalIndex += 1;
                        } else if (values.length == 1) {
                            horizontalIndex += 2;
                        } else if ((attribute) % 3 === 2 && attribute / 3 < 12) {
                            horizontalIndex++;
                        }
                        // Break the loop if we run out of pasted values
                        break;
                    }
                    updatedValues[horizontalIndex - 1] = values[index]
                        ?.trim();
                    index++;

                    horizontalIndex++;

                }
            }
        });

        debugger
        if (horizontalValues.length -= verticalValues.length) {
            var index = 0;

        }
        setTimeout(() => {
            // Your handler logic goes here You can update the state or perform any other
            // actions here
            setInputValues(updatedValues);
        }, 10);
    };

    return (
        <div className='row'>
            <div className='col-4'>
                <input
                    name={`text1`}
                    attr="1"
                    value={inputValues[0] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>
            </div>
            <div className='col-4'>
                <input
                    name={`text2`}
                    attr="2"
                    value={inputValues[1] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text3`}
                    attr="3"
                    value={inputValues[2] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>

            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="4"
                    value={inputValues[3] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="5"
                    value={inputValues[4] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="6"
                    value={inputValues[5] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="7"
                    value={inputValues[6] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="8"
                    value={inputValues[7] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="9"
                    value={inputValues[8] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="10"
                    value={inputValues[9] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>

            </div>
            <div className='col-4'>
                <input
                    name={`text4`}
                    attr="11"
                    value={inputValues[10] || ''}
                    onChange={(e) => handleInputChange(e)}
                    onPaste={(e) => {
                    handlePaste(e)
                }}/>
            </div>
        </div>
    )
}

export default MultipleInputFields;

Copy Paste Functionality in the React Input field

How should i refresh my div content without interupt any of my JS functionand reload the entire page?

This is my code. Hopefully, someone can give me a solution.

``
</kbd>

<kbd><style type="text/css">
#myGame1 {
  display: none;
}
#myGame2 {
  display: none;
}
#myGame3 {
  display: none;
}
#myMenu1 {
  display: block;
}
#myCanvas{
visibility: hidden;
}

</style></kbd>

<kbd><body oncontextmenu="return false;" onkeydown="return (event.ctrlKey && event.shiftKey && event.keyCode === 73) ? false : true;">
<div id="clouds">
    <div class="cloud x1"></div>
    <div class="cloud x2"></div>
    <div class="cloud x3"></div>
    <div class="cloud x4"></div>
    <div class="cloud x5"></div>
</div></kbd>


<kbd><?php
    require_once("function/function.php");
    get_header();
?></kbd>

<kbd><div id="myMenu1">
  <?php
    require_once("function/function.php");
    get_menu();
  ?>
</div>
</kbd>
<kbd><div  id="myGame1">
  <?php
    require_once("function/function.php");
    get_boatgame();
  ?>
</div></kbd>

<kbd><div  id="myGame2">
  <?php
    require_once("function/function.php");
    get_meowgame();
  ?>
</div></kbd>

<kbd><div  id="myGame3">
  <?php
    require_once("function/function.php");
    get_cabardiri();
  ?>
</div></kbd>

<kbd></body>
</html>
<script>
function myFunctionGame1() {
  var x = document.getElementById("myGame1");
  var y = document.getElementById("myMenu1");

  if (x.style.display === "block") {

    x.style.display = "none";
    y.style.display = "block";

  } else {

    x.style.display = "block";
    y.style.display = "none";

  }
}
function myFunctionGame2() {
  var x = document.getElementById("myGame2");
  var y = document.getElementById("myMenu1");
  var canvasgame = document.getElementById("myCanvas");
  if (x.style.display === "block") {
    x.style.display = "none";
    y.style.display = "block";
    canvasgame.style.visibility= "hidden";
  } else {
    x.style.display = "block";
    y.style.display = "none";
    canvasgame.style.visibility= "visible";
  }
}
function myFunctionGame3() {
  var x = document.getElementById("myGame3");
  var y = document.getElementById("myMenu1");
  if (x.style.display === "block") {
    x.style.display = "none";
    y.style.display = "block";
  } else {
    x.style.display = "block";
    y.style.display = "none"
  }
}

function myFunctionhome1() {
  var x = document.getElementById("myGame1");
  var y = document.getElementById("myMenu1");

  if (x.style.display === "none") {

    x.style.display = "block";
    y.style.display = "none";
  } else {
    x.style.display = "none";
    y.style.display = "block";
       
  }
}

function myFunctionhome2() {
  var x = document.getElementById("myGame2");
  var y = document.getElementById("myMenu1");
  var canvasgame = document.getElementById("myCanvas");
  if (x.style.display === "none") {
    x.style.display = "block";
    y.style.display = "none";
    canvasgame.style.visibility= "visible";
  } else {
    x.style.display = "none";
    y.style.display = "block"
    canvasgame.style.visibility= "hidden";
  }
}
function myFunctionhome3() {
  var x = document.getElementById("myGame3");
  var y = document.getElementById("myMenu1");
  if (x.style.display === "none") {
    x.style.display = "block";
    y.style.display = "none";
  } else {
    x.style.display = "none";
    y.style.display = "block"
  }
}
</script></kbd>
``

I’m doing my final year project on developing a game. The game should be refreshed on its own after the user clicks the back button. I tried to put

``
<kbd>$('#myGame1').load(location.href + ' #myGame1');</kbd>
``

in my javascript

but it’s not working. My div becomes hidden after I click the game button because of the CSS in my javascript.

HighCharts Map Drilldown – Map is rotating 180 degrees after Drillup

I am using HighCharts Map and using json data to render the USA map (I have used an SVG file and converted the SVG into json using https://highcharts.github.io/map-from-svg/ tool). I am implementing drill-down feature in the map. The drill-down works but when I click “USA” in the breadcrumb, the map rotates by 180 degrees. The expected behavior should be – The USA map should not be upside down after the drill up. I am not sure what’s wrong with my code. Can anyone please provide guidance to fix the issue?

To reproduce the issue in the fiddle –

  1. Click on any state in the USA map (i.e California)
  2. Now click “USA” in the breadcrumbs
  3. Issue – USA map is upside down now.

The complete code – https://jsfiddle.net/seaxfdrz/7/

The code snippet is –

Highcharts.mapChart('container', {
    chart: {
        events: {
            drilldown,
            afterDrillUp
        }
    },

    title: {
        text: 'Highcharts Map Drilldown'
    },

    //mapView,

    mapNavigation: {
        enabled: true,
        buttonOptions: {
            verticalAlign: 'bottom'
        }
    },

    plotOptions: {
        map: {
            states: {
                hover: {
                    color: '#EEDD66'
                }
            }
        }
    },

    series: mapJason,

    drilldown: {
        activeDataLabelStyle: {
            color: '#FFFFFF',
            textDecoration: 'none',
            textOutline: '1px #000000'
        },
        breadcrumbs: {
            floating: true,
            relativeTo: 'spacingBox'
        },
        drillUpButton: {
            relativeTo: 'spacingBox',
            position: {
                x: 0,
                y: 60
            }
        }
    }
});

How can i change translateX value when a button is clicked?

I’m new to react. I wanna make my button change the translateX value when it is clicked by amount of 1170px, but when i checked the site i quite don’t get how the onClick attribute is rendered in reactjs.

Here is the code:

function Slideshow() {
  const slider = [
    { name: slide_logo_1, link: "https://timesrecords.lnk.to/CITOPIA" },
    {
      name: slide_logo_2,
      link: "https://store.hangdiathoidai.com/search?q=lana+del+rey",
    },
    { name: slide_logo_3, link: "https://timesrecords.lnk.to/TocTien-Cong" },
    { name: slide_logo_4, link: "https://timesrecords.lnk.to/TSMidnights" },
    { name: slide_logo_5, link: "https://timesrecords.lnk.to/LINK-HTL" },
  ];
  const getTranslateX = () => {
    var myElement = document.querySelector(".owl-wrapper");
    var style = window.getComputedStyle(myElement);
    var matrix = new DOMMatrix(style.transform);
    <Alert>{matrix}</Alert>
    
  };

  return (
    <section>
      <div className="wrapper">
        <div className="inner space-30 section-slider">
          <div
            className="slider-carousel owl-carousel owl-theme"
            id="slider-carousel"
            data-mobile="[479,1]"
            data-tabletsmall="[768,1]"
            data-desktopsmall="[979,1]"
            data-desktop="[1199,1]"
            data-pagination="false"
            data-navigation="true"
            data-autoplay="5000"
            data-items="1"
            style={{ display: "block", opacity: 1 }}
          >
            <div
              className="owl-wrapper-outer autoHeight"
              style={{ height: 431 }}
            >
              <div
                className="owl-wrapper"
                style={{
                  width: 11700,
                  left: 0,
                  display: "block",
                  transition: `all 400ms ease 0s`,
                  transform: `translate3d(0px, 0, 0)`,
                }}
              >
                {slider.map((products, index) => {
                  return (
                    <div className="owl-item" style={{ width: 1170 }}>
                      <div className="text-center">
                        <Link
                          className="slide"
                          to={products.link}
                          title=""
                          key={index}
                        >
                          <img src={products.name} alt="" />
                        </Link>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="owl-controls clickable">
              <div className="owl-buttons">
                <div
                  className="sangtrai owl-prev"
                  onClick={getTranslateX}
                ></div>
                <div className="sangphai owl-next"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

export default Slideshow;

The thing in here is when i click .sangtrai, the translateX value in .owl-wrapper’s transform will be added by amount of 1170px and when i click .sangphai, the translateX value in .owl-wrapper’s transform will be reduced by amount of 1170px

How do I register inputs only if they have value with React-form-hook?

As of right now my code registers all inputs, whether or not they have any value. How can I change my code so it only registers inputs only when there is value?

import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" {...register("example")} />
      
      <input {...register("exampleRequired", { required: true })} />
      {errors.exampleRequired && <span>This field is required</span>}
      
      <input type="submit" />
    </form>
  );
}

Fill arrow SVG icon using percentage value from specific point

I have this svg icon that I want to fill with color according to the percentage value, it’s a chart, so it should start from the top left and fill all the way to the right following the line..

Demo

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 254.25 233.26">
<defs>
 <linearGradient id="progress" x1="1" y1="0" x2="0" y2="0">
      <stop id="stop1" offset="0" stop-color="#bb8e89"/>
      <stop id="stop2" offset="0" stop-color="#f4b6b0"/>
    </linearGradient>
</defs>
<g id="Capa_2" data-name="Capa 2">
<g id="Capa_1-2" data-name="Capa 1">
<path class="cls-1" fill="url(#progress)" d="M254.25,17.72,235.32,0,216.38,17.72H227V92.93c0,66.6-25.41,124.48-104.17,124.48S18.63,159.53,18.63,92.93V52.35H0V92.14c0,76.11,32.18,141.12,122.79,141.12,89.77,0,122-65,122-141.12V17.72Z"/>
</g>
</g>
</svg>
function setProgress(amt)
{
  amt = (amt < 0) ? 0 : (amt > 1) ? 1 : amt;
  document.getElementById("stop1").setAttribute("offset", amt);
  document.getElementById("stop2").setAttribute("offset", amt);
}


setProgress(0.60);```

How to add a dropbox upload button to a retool app

Hi I am trying to create a dropbox upload button in custom component in retool. This is the code I am using however it only lets me select a file but does not upload it or interact with dropbox:

<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="MY_APP_KEY"></script>

<script>
  function uploadFile(files) {
    var file = files[0]; // Get the first file from the selected files

    var accessToken = 'MY_ACCESS_TOKEN'; // Replace with your access token

    var dbx = new Dropbox.Dropbox({ accessToken: accessToken });
    dbx.filesUpload({ path: '/' + file.name, contents: file })
      .then(function (response) {
        console.log('File uploaded successfully!', response);
      })
      .catch(function (error) {
        console.error('Error uploading file.', error);
      });
  }
</script>

<input type="file" id="fileInput" onchange="uploadFile(this.files)" />

I have entered my access token and app key correctly so I am not sure what the problem is, where am I going wrong?

JavaScript solution to “Fraudulent Activity Notifications” on Hackerrank is passing initial tests but failing the others

Below is my attempt to solve this Hackerrank problem in JavaScript. The code passes all initial tests. I have done some debugging and I think the logic is correct. My general approach is to store counts of the array in a map, like a counting sort algorithm, and to find the median based on a moving medianIndex. I am open to better approaches, but I would like to understand why my code is producing a “wrong answer” (not timing out) for the larger tests with arrays of length 200,000.

function activityNotifications(expenditure, trailingDays) {
    // Write your code here
    let notices = 0
    // Create map to store counts of each expenditure
    const expendituresMap = new Map()
    
    // Add expenditure counts to map
    for (let i = 0; i < expenditure.length; i++) {
        expendituresMap.set(expenditure[i], (expendituresMap.get(expenditure[i]) || 0) + 1)
    }
    

    // Determine median index of trailing days only
    let medianIndex = 0
    let even = trailingDays % 2 === 0 ? true : false
    if (even) {        
        // First/left median
        medianIndex = trailingDays / 2 - 1
    } else {
        medianIndex = Math.floor(trailingDays / 2)
    }

    for (let i = trailingDays; i < expenditure.length; i++) {
        // Get median value using expenditures map
        let median = getMedian(even, medianIndex, expendituresMap)        
        
        // Advance median index one spot on each iteration
        medianIndex++
        
        // Check if notice should be sent
        if (expenditure[i] >= median * 2) notices++;
    }    
    return notices
}

function getMedian(even, medianIndex, expendituresMap) {
    let count = 0    
    // Create second median index for calculating median of even trailing days
    let medianIndex2 = medianIndex + 1
    
    let middleLeft = 0
    let middleRight = 0

    // Locate median from map using median index
    let median = 0
            
    // Iterate through map; values are like the index in an imaginary sorted expenditure array
    for (const [key, value] of expendituresMap) {
        // Advance count by value (index of sorted expenditure array)
        count += value
        
        // If count is > median 
        if (count > medianIndex) {            
            if (even) {
                if (middleLeft === 0) {
                    // Set middleLeft only if it hasn't been set yet
                    middleLeft = key                     
                    // Check if middle right should also be set (is the same number)
                    if (count > medianIndex2) {
                        middleRight = key
                    }
                    // middleLeft is set but not middleRight, so try next loop
                    else continue
                } else {
                    // middleLeft is already set; now set middleRight
                    if (count > medianIndex2) {
                        middleRight = key                        
                    } else continue                    
                }
                median = (middleLeft + middleRight) / 2
                break
            } else {
                // Trailing days are odd, so median is the key
                median = key
                break                    
            }
        }            
    }
    return median
}