About calling multiple APIs while catching user input events in React (beginner)

I am developing a React application as a beginner, when the user types in the search box, I need to send a request (API call) to get suggested results. However, if I call the API immediately every time the user types each character, it will be resource-consuming and have a bad experience and have to load many times.

I tried delaying it by 500ms, but the result still calls many APIs

function bindInputWithDelay(selector, callback) {
  const inputEl = document.querySelector(selector);
  if (!inputEl) return;

  inputEl.addEventListener('input', (event) => {
    const value = event.target.value;
    setTimeout(() => {
      callback(value);
    }, 500);
  });
}

Please help me write a function that will wait for the user to finish typing and then send the API only once, the waiting time can be 500ms.

If it’s a custom React Hook, that’s even better.

Thanks.

issues on mobile with overflow:hidden and splide slider

I’m using splide on my webflow site to create a services slider. on desktop it works great and in the mobile preview on desktop, it also works. the problem starts when i try and view it on my phone, the content on each slide glitches in and out during each transition. I had the whole section that holds the splide slider set to overflow:hidden so it doesnt get the horizontal scroll bar, when i turned that off, it was working normally on mobile again.

this is my webflow link: https://platinum-medical.webflow.io

I tried making the whole body overflow:hidden but that still broke it, i also tried setting the splide__track to a specific width but i still get the horizontal scroll issue.

here is my code (CSS & JS):

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/css/splide-core.min.css">
<style>
.splide__track {
  overflow: visible;
}
</style>

<script src="https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/js/splide.min.js"></script>
<script>

function slider1() {

let splides = $('.slider_model');
for ( let i = 0, splideLength = splides.length; i < splideLength; i++ ) {
    new Splide( splides[ i ], {
  // Desktop on down
    autoplay: true,
  interval: 3000,
  perPage: 3,
    perMove: 1,
  focus: 'center', // 0 = left and 'center' = center
  type: 'loop', // 'loop' or 'slide'
  gap: '.5em', // space between slides
  arrows: 'false', // 'slider' or false
  pagination: 'false', // 'slider' or false
  speed : 1000, // transition speed in miliseconds
  dragAngleThreshold: 30, // default is 30
  autoWidth: false, // for cards with differing widths
  rewind : false, // go back to beginning when reach end
  rewindSpeed : 400,
  waitForTransition : true,
  updateOnMove : true,
  trimSpace: false, // true removes empty space from end of list
  breakpoints: {
        991: {
    perPage: 2,
        // Tablet
        },
    767: {
        // Mobile Landscape
      perPage: 2,
      
        },
    479: {
        // Mobile Portrait
      perPage: 1,
        }
    }
} ).mount();
}

}
slider1();

</script>

This is the animation css for the active slide

<style>

.splide__slide.is-active .service_slider-content{
opacity: 100%;
transform: translate(0%);
}

.splide__slide.is-active .slider_mood{
transform:scale(1);
}

</style>

What I would like my site to look like, without the horizontal scrolling

screen recording of the glitch on my phone -> https://drive.google.com/file/d/1Gr0oznD2Q6qs3X1cblGvKSVnPAuVPKkK/view?usp=sharing

I swear i googled and searched the splide docs before making this post, please, if the answer was obvious i would love to be humbled :’)

A Function with average complexity O(n log n), to count the number of queries that a user queries the most

I am developing an algorithm to filter and count the number of words that users query the most.

I have an array of queries consisting of strings representing the keywords that users search for in a day, for example:

const queries = [
"weather today", "openai", "javascript arrays", "weather today",
"news", "javascript arrays", "open", "javascript arrays",
"recipe", "news", "openai", "weather today"
];

Need to:

Average complexity O(n log n)

My function is writing but it is not running correctly:

function topKFrequent(queries, k) {
  const freqMap = {};
  for (const q of queries) {
    freqMap[q] = (freqMap[q]) + 1;
  }

  const entries = Object.entries(freqMap);
  entries.sort((a, b) => {
    let countA = a[1], countB = b[1];
    if (countA != countB) {
      return countB - countA;  
    }
    return a[0].localeCompare(b[0]);
  });

  return entries.slice(0, k).map(entry => entry[0]);
}

With:

queries – array of search strings.

k– number of most popular keywords to return.

I run the following command console.log(topKFrequent(queries, 2));

It outputs [ 'weather today', 'openai' ], and actually I was expecting ["javascript arrays", "weather today"], because "javascript arrays", and "weather today" both appear 3 times while "openai" appears exactly 2 times.

Expected result:

["javascript arrays", "weather today"]

Average complexity O(n log n)

Thanks.

Issue with trying to focus textarea on doubleClick

I want my textarea to focus on double click for that i have the component below

[Ignore the setIsEditing its just for css]

-> The textarea is readOnly by default.

Expected behaviour: on double click, the readOnly state will be set to false and then the textarea should foucs

Current behaviour: the readOnly state is set to false and the textarea is editable BUT the textarea.current?.focus() fails/doesn’t work

export function EditableText({
  title,
  className,
  outlineOnDoubleClick = false,
  outlineOnClick = true,
}: EditableInputProps) {
  const [inputVal, setInputVal] = useState(title);
  const [isEditing, setIsEditing] = useState(false);
  const [readOnly, setReadOnly] = useState(true);
  const textAreaRef = useRef<null | any>(null);

  const baseClass = `resize-none select-none`;
  const outlineDblClass = `${!isEditing && outlineOnDoubleClick ? "outline-none" : ""}`;
  const outlineSingleClass = `${outlineOnClick ? "" : !outlineOnDoubleClick && "outline-none"}`;
  const finalClass = cn(
    baseClass,
    outlineSingleClass,
    outlineDblClass,
    className,
  );

  return (
    <textarea
      ref={textAreaRef}
      value={inputVal}
      onChange={(e) => setInputVal(e.target.value)}
      className={finalClass}
      readOnly={readOnly}
      onDoubleClick={() => {
        setIsEditing(true);
        setReadOnly(false);
        textAreaRef.current?.focus();
      }}
      onBlur={() => {
        setIsEditing(false);
        setReadOnly(true);
      }}
    />
  );
}

How can I disable drag and drop in Dropzone.js?

I am working on a file uploader with the help of the JavaScript library Dropzone.

The file uploader is intended to also work as a image preview box.

The uploader should take only one file. For this purpose I use these lines to disable click unless there is no image:

if (file.name !== "") {
    myDropzone.options.clickable = false
}

I am showing an image placeholder when no upload is done.

Dropzone.autoDiscover = false

var myOptions = {
  url: window.location.pathname,
  autoProcessQueue: false,
  uploadMultiple: false,
  parallelUploads: 1,
  maxFiles: 1,
  paramName: name,
  thumbnailWidth: 1200,
  thumbnailHeight: 900,
  addRemoveLinks: true,
  dictRemoveFile: '<i class="fa fa-remove"></i>',
  dictDefaultMessage: "Drag an image here to upload, or click to select one",
}

var myDropzone = new Dropzone(document.querySelector(".dropzone"), myOptions)
var currentFile = { name: "Existing file" }
myDropzone.options.addedfile.call(myDropzone, currentFile)
myDropzone.options.thumbnail.call(
  myDropzone,
  currentFile,
  "https://placehold.co/1200x900",
)
myDropzone.options.accept = function (file) {
  if (file.name !== "") {
    myDropzone.options.clickable = false
  }
}
.form-label {
  font-weight: 500;
}

.file-upload-default {
  display: none;
}

.dropzone {
  padding: 0 !important;
  border: 1px solid #dee2e6 !important;
  border-radius: 6px;
  overflow: hidden !important;
}

/* .dropzone .dz-details, */
.dropzone .dz-filename,
.dropzone .dz-progress {
  display: none;
}

.dropzone .dz-preview {
  display: block;
  margin: 0 !important;
}

.dropzone .dz-details {
  height: auto !important;
}

.dropzone .dz-preview .dz-image {
  border-radius: 0 !important;
  width: 100% !important;
  height: auto !important;
}

.dropzone .dz-preview .dz-image img {
  max-width: 100%;
  height: auto !important;
  overflow: visible !important;
  border-radius: 0;
  transform: scale(1) !important;
  filter: blur(0) !important;
}

.dropzone .dz-preview .dz-remove {
  text-decoration: none !important;
  width: 36px;
  height: 36px;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  font-family: "Font Awesome";
  font-size: 18px;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 21;
  display: none !important;
}

.dropzone .dz-preview:hover .dz-remove {
  display: flex !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>

<div class="container">
  <form method="post" action="/upload" class="my-2">
    <div class="mb-3">
      <label for="pwd" class="form-label mb-1">Full name:</label>
      <input
        type="text"
        class="form-control"
        id="fullname"
        placeholder="Enter your full name"
        name="full-name"
      />
    </div>

    <div class="mb-3 mt-3">
      <label for="file" class="form-label mb-1">Post image</label>
      <div class="dropzone">
        <input name="file" type="file" id="file" class="file-upload-default" />
      </div>
    </div>
  </form>
</div>

What I have been unable to do is also disable drag and drop.

How do I achieve that?

How can I disable drag and drop in Dropjone.js?

I am working on a file uploader with the help of the JavaScript library Dropzone.

The file uploader is intended to also work as a image preview box.

The uploader should take only one file. For this purpose I use these lines to disable click unless there is no image:

if (file.name !== "") {
    myDropzone.options.clickable = false
}

I am showing an image placeholder when no upload is done.

Dropzone.autoDiscover = false

var myOptions = {
  url: window.location.pathname,
  autoProcessQueue: false,
  uploadMultiple: false,
  parallelUploads: 1,
  maxFiles: 1,
  paramName: name,
  thumbnailWidth: 1200,
  thumbnailHeight: 900,
  addRemoveLinks: true,
  dictRemoveFile: '<i class="fa fa-remove"></i>',
  dictDefaultMessage: "Drag an image here to upload, or click to select one",
}

var myDropzone = new Dropzone(document.querySelector(".dropzone"), myOptions)
var currentFile = { name: "Existing file" }
myDropzone.options.addedfile.call(myDropzone, currentFile)
myDropzone.options.thumbnail.call(
  myDropzone,
  currentFile,
  "https://placehold.co/1200x900",
)
myDropzone.options.accept = function (file) {
  if (file.name !== "") {
    myDropzone.options.clickable = false
  }
}
.form-label {
  font-weight: 500;
}

.file-upload-default {
  display: none;
}

.dropzone {
  padding: 0 !important;
  border: 1px solid #dee2e6 !important;
  border-radius: 6px;
  overflow: hidden !important;
}

/* .dropzone .dz-details, */
.dropzone .dz-filename,
.dropzone .dz-progress {
  display: none;
}

.dropzone .dz-preview {
  display: block;
  margin: 0 !important;
}

.dropzone .dz-details {
  height: auto !important;
}

.dropzone .dz-preview .dz-image {
  border-radius: 0 !important;
  width: 100% !important;
  height: auto !important;
}

.dropzone .dz-preview .dz-image img {
  max-width: 100%;
  height: auto !important;
  overflow: visible !important;
  border-radius: 0;
  transform: scale(1) !important;
  filter: blur(0) !important;
}

.dropzone .dz-preview .dz-remove {
  text-decoration: none !important;
  width: 36px;
  height: 36px;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  font-family: "Font Awesome";
  font-size: 18px;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 21;
  display: none !important;
}

.dropzone .dz-preview:hover .dz-remove {
  display: flex !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>

<div class="container">
  <form method="post" action="/upload" class="my-2">
    <div class="mb-3">
      <label for="pwd" class="form-label mb-1">Full name:</label>
      <input
        type="text"
        class="form-control"
        id="fullname"
        placeholder="Enter your full name"
        name="full-name"
      />
    </div>

    <div class="mb-3 mt-3">
      <label for="file" class="form-label mb-1">Post image</label>
      <div class="dropzone">
        <input name="file" type="file" id="file" class="file-upload-default" />
      </div>
    </div>
  </form>
</div>

What I have been unable to do is also disable drag and drop.

How do I achieve that?

Is there a way to edit a Range without discarding other existing Ranges?

I am attempting to perform operations on multiple text selections by using a loop, that runs after pressing a button.

Because each iteration of the loop makes changes to the highlighted nodes, I need to alter each Range’s start and end point accordingly.

The issue is: accessing the Range.setStart and Range.setEnd methods, whilst multiple selections exist seems to discard all Ranges – i.e. all text gets deselected. Furthermore, the Selection.type property gets changed from “Range” to “Caret”. None of this happens if only one selection is made.

Am I doing something wrong, or is this a bug?

I’ve spend a considerable amount of time on trying to avoid this issue, but to no avail. I would greatly appreciate an expertly voice on the topic.

And just for clarity:
I am using a Firefox-based browser.
I making multiple selections by holding down CTRL, whilst click-dragging the cursor.
I access the resulting Ranges with the following code:

const selection = window.getSelection()
const range = selection.getRangeAt(index)

Postgres UPDATE table SET jsonb typed collum with javascript var not work for remove an array item

I’m using this package to CRUD in a Postgres database https://github.com/porsager/postgres

This is my query:
This work fine to remove a index 0 or n… on a array data inside a jsonb collum,

POSTGRES_SQL`
  UPDATE pedidos
  SET
    objeto = objeto - 0
  WHERE _id = '123abc';
`

if use javascript var in _id on WHERE, this work normally

const _id = '123abc'

POSTGRES_SQL`
  UPDATE pedidos
  SET
    objeto = objeto - 0
  WHERE _id = ${_id};
`

but, if use var in index 0/n… inside a SET, like this

const _id = '123abc'
const INDEX_TO_REMOVE = 0 // (or '0' or 1 or '1' or n...)

POSTGRES_SQL`
  UPDATE pedidos
  SET
    objeto = objeto - ${INDEX_TO_REMOVE}
  WHERE _id = ${_id};
`

not Work, entrie not as removed, but not show any error, if use like this

const _id = '123abc'
const INDEX_TO_REMOVE = 0 // (or '0' or 1 or '1' or n...)

POSTGRES_SQL`
  UPDATE pedidos
  SET
    objeto = objeto - ${INDEX_TO_REMOVE}
  WHERE _id = '${_id}';
`

return error could not determine data type of parameter $1.

i tried, objeto = objeto - ${INDEX_TO_REMOVE}::text and objeto = (objeto::jsonb - ${INDEX_TO_REMOVE})::text and objeto = (objeto::jsonb - ${INDEX_TO_REMOVE}::text)::jsonb and nothin work, how use javascript var inside a set to perform delete an index inside an array?

Relationed to: https://stackoverflow.com/a/79655539/2741415

Prevent Change Value from Google Sheet Arrayformula

I’m trying to “freeze” (make permanent) certain rows in my Google Sheet. These rows get their data from another spreadsheet using IMPORTRANGE. My goal is for these specific rows to keep their current values, even if the original data in the other spreadsheet changes.

The problem is, I use an ARRAYFORMULA to bring in the data. When I try to “freeze” a row (by having a script replace its formula with a static value), the ARRAYFORMULA stops working. It throws an error because it needs all its output cells to be empty, and my “frozen” row now occupies those cells.

function freeze() {
  var spreadsheet = SpreadsheetApp.getActive(); // Gets the active spreadsheet.
  var ui = SpreadsheetApp.getUi(); // Gets the user interface environment for pop-up messages.

  // Retrieves the range currently selected by the user.
  var selectedRange = spreadsheet.getActiveRange();

  // Checks if a range was actually selected.
  if (!selectedRange) {
    // Displays an error alert if no range is selected.
    ui.alert('Error', 'No range selected. Please select a range on the sheet before running the script.', ui.ButtonSet.OK);
    return; // Exits the function.
  }

  // Asks the user for confirmation before proceeding with the freeze operation.
  var response = ui.alert(
    'Freeze Values', // Title of the confirmation dialog.
    'Confirm you want to freeze values in the selected range: ' + selectedRange.getA1Notation() + '?', // Message including the selected range.
    ui.ButtonSet.YES_NO // Provides 'Yes' and 'No' buttons.
  );

  // Proceeds only if the user confirms by clicking 'Yes'.
  if (response == ui.Button.YES) {
    try {
      // Copies the values from the selected range and pastes them back onto the same range.
      // This effectively replaces any formulas with their static calculated values.
      selectedRange.copyTo(selectedRange, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      
      // Displays a success alert to the user.
      ui.alert('Success', 'Values frozen for the range: ' + selectedRange.getA1Notation(), ui.ButtonSet.OK);

    } catch (e) {
      // Catches and handles any errors that might occur during the operation (e.g., invalid range).
      ui.alert('Error', 'An error occurred during the operation: ' + e.message, ui.ButtonSet.OK);
    }
  } else {
    // Displays an alert if the user cancels the operation.
    ui.alert('Cancelled', 'Operation cancelled.', ui.ButtonSet.OK);
  }
}

Throws this formula error:

Error

Array result was not expanded because it would overwrite data in F19.

.NET vs. Node.js for Real-Time Apps (WebSockets) – Performance, Scalability, and Future Trends

I’m evaluating backend technologies for a high-traffic real-time application (e.g., live chat, gaming, or stock trading) and need to choose between .NET (Core/6+) and Node.js.

Tested a basic chat app:

Node.js + Socket.IO: Easy setup but struggled with CPU-heavy tasks.

.NET + SignalR: More boilerplate but handled threads better.

Expected Node.js to lead in throughput, but .NET’s thread pool surprised me.

Multiple cell copy pasting just like spreadsheets. Text+Images both

I am looking for something Similar to Google sheets/MS Excel. But with few things of my own.

It is really easy to input data in Excel and that’s what my end user loves.

So, actually I am looking for some library / package or even any third party made tool.

Requirements:

  • Can move across different cells using arrow keys.

  • Paste image into cells.

-Copy paste multiple cells from one place to another.

-Merge Cells.

I cam across multiple libraries but none of them seems to solve all the problems.

Handontable – Doesn’t natively supports image inside cells.

AGrid – No cell merging,

Luckysheet – Most close, only problem is that I can’t put an image into a cell. Images float everywhere and it’s hard to track them.

So, in my case user will input some data in a row and then will copy paste the image. That image has to be tied to the data in the row. I want the image to be uploaded onto the Database so that I can use it seamlessly.

Help me on how this can be achieved.

How do I set a default or current image in Dropzone.js?

I am working on a file uploader with the help of the JavaScript library Dropzone.

The file uploader si intended to also work as a image preview system.

Because there should be an image preview for existing items that the user wants to update, I need to show a default or current image.

Dropzone.autoDiscover = false

let dz = document.querySelector(".dropzone")
var myDropzone = new Dropzone(dz, {
  url: window.location.pathname,
  autoProcessQueue: false,
  uploadMultiple: false,
  parallelUploads: 1,
  maxFiles: 1,
  paramName: name,
  thumbnailWidth: 1200,
  thumbnailHeight: 900,
  addRemoveLinks: true,
  dictRemoveFile: '<i class="fa fa-remove"></i>',
  dictDefaultMessage: "Drag an image here to upload, or click to select one",
  accept: function (file, done) {
    if (file.name == "https://placehold.co/1200x900") {
    } else {
      done()
    }
  },
})
.form-label {
  font-weight: 500;
}

.file-upload-default {
  display: none;
}

.dropzone {
  padding: 0 !important;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  overflow: hidden !important;
}

/* .dropzone .dz-details, */
.dropzone .dz-filename,
.dropzone .dz-progress {
  display: none;
}

.dropzone .dz-preview {
  display: block;
  margin: 0 !important;;
}

.dropzone .dz-details {
  height: auto !important;
}

.dropzone .dz-preview .dz-image {
  border-radius: 0 !important;
  width: 100% !important;
  height: auto !important;
}

.dropzone .dz-preview .dz-image img {
  max-width: 100%;
  height: auto !important;
  overflow: visible !important;
  border-radius: 0;
  transform: scale(1) !important;
  filter: blur(0) !important;
}


.dropzone .dz-preview .dz-remove {
  text-decoration: none !important;
  width: 36px;
  height: 36px;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  font-family: "Font Awesome";
  font-size: 18px;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 21;
  display: none !important;
}

.dropzone .dz-preview:hover .dz-remove {
  display: flex !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>

<div class="container">
  <form method="post" action="/upload" class="my-2">
    <div class="mb-3">
      <label for="pwd" class="form-label mb-1">Full name:</label>
      <input
        type="text"
        class="form-control"
        id="fullname"
        placeholder="Enter your full name"
        name="full-name"
      />
    </div>

    <div class="mb-3 mt-3">
      <label for="file" class="form-label mb-1">Post image</label>
      <div class="dropzone">
        <input name="file" type="file" id="file" class="file-upload-default" />
      </div>
    </div>
  </form>
</div>

How do I achieve that?

Nuxt3: A funcion can behave differently depending on the execution context (server-side or client-side)

I’m using Nuxt 3.

I’m trying to create a utility function called dynamicFetch that can behave differently depending on the execution context (server-side or client-side).

The idea is to allow developers to use it both inside setup() and lifecycle hooks like onMounted, and based on where it’s running, it will call the appropriate fetch method.

export async function dynamicFetch({
  path = "",
  options = {},
}: {
  path: string;
  options?: any;
}): Promise<any> {
  // do something

  return process.server || nuxtApp.isHydrating
    ? useFetch(...)
    : $fetch.raw(...)
}

So if case like below

<script setup>
const res = await dynamicFetch('/api/...')

when running on server-side it would call useFetch.
when running on client-side it would still call useFetch, that correctly.

but if the case like below

<script setup>
onMounted(async () => {
  const res = await dynamicFetch('/api/...')
})

when running on server-side it would not do anything.
when running on client-side, it would call useFetch instead of $fetch, which is not the result I want.

Has anyone tried implementing a dynamic fetch function like this?
How would you structure it to conditionally use useFetch or $fetch based on environment and timing?

Getting Error while using Cron Job Schedular in Node.js

const parts = dateFormat.formatToParts(date).filter(part => {
‘RangeError: Invalid time value’. at DateTimeFormat.formatToParts
()
at buidDateParts

getting error in Cron Job Schedular using with node ‘20.18.3’ and “node-cron”: “^4.0.5”.
is there any Javascript date problem, i have tested with moment but same error.

cron.schedule('* * * * *', async() => {

  try {
    await jobSchedular.turnOffActivity();
  } catch (error) {
    console.log(error);
    
  }
});


exports.turnOffActivity = async () => {
  
  try {
    const now = new Date();
     
    const result = await Post.update(
      { is_active: false },
      {
        where: {
          end_time: { [Op.lte]: now },
          is_active: true,
          type:{[Op.in]:['liveactivity','plannedactivity']}
        }
      }
    );

  } catch (error) {
    console.error('Error turning off activities:', error);
  }
};

How to find the maximum sub-array of element products?

I am developing a financial investment application. The user tracks a series of percentage changes in stock prices each day.

For example, they have data for the last 10 days in an array:

let dailyChanges = [1.05, 0.9, 1.1, 0.95, 1.2, 0.8, 1.3];

Where:

  • 1.05 means +5%
  • 0.9 means -10%
  • 1.2 means +20%
  • 0.8 means -20%

Help me write a function to find which consecutive series of days gives the highest profit when multiplying the changes together.

My function:

function maxProfitStreak(arr) {
  let maxProd = 0;
  let minProd = 0;
  let result = 0;

  for (let i = 0; i < arr.length; i++) {
    let current = arr[i];
    let prevMax = maxProd;

    maxProd = Math.max(current, current * maxProd, current * minProd);
    minProd = Math.min(current, current * prevMax, current * minProd);

    result = Math.max(result, maxProd);
  }

  return result;
}

What did you try?

I called the function maxProductSubarray([2, 3, -2, 4]) in the browser console.

What did you expect?

I expected it to return 6, since [2, 3] is the subarray with the largest product.

What actually happened?

It returned -2, which is incorrect. I realized that I did not initialize maxProd and minProd properly in my function.