Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object.

You can view the code on codesanbox

The array I have is sorted using the following comparison method:

interface Comparator<A> {
  (first: A, second: A): number;
}

function compareFields<A>(key: keyof A): Comparator<A> {
  return (a: A, b: A): number => {
    const first = a[key];
    const second = b[key];

    if (first < second) {
      return 1;
    } else if (first > second) {
      return -1;
    } else {
      return 0;
    }
  };
}

To find the index, I am using the binarySearch method

function binarySearch<A>(
  source: A[],
  target: A,
  comparator: Comparator<A>,
): number {
  let first = 0;
  let last = source.length - 1;

  while (first <= last) {
    const middle = (first + last) >>> 1;
    const compareResult = comparator(source[middle], target);

    if (compareResult === 0) {
      return middle;
    } else if (compareResult > 0) {
      last = middle - 1;
    } else {
      first = middle + 1;
    }
  }

  return -1;
}

Finally, I try to find the correct index and use the Array.splice method to add the new object to the source array

function binaryInsert<A extends any>(
  source: A[],
  target: A,
  comparator: Comparator<A>,
): A[] {
  const index = binarySearch(source, target, comparator);
  return source.splice(index, 0, target);
}
const source = [
  { foo: 0 },
  { foo: 2 },
  { foo: 4 },
  { foo: 6 },
  { foo: 8 },
];
const expect = [
  { foo: 0 },
  { foo: 2 },
  { foo: 4 },
  { foo: 6 },
  { foo: 7 },
  { foo: 8 },
];
const target = { foo: 7 };
const result = binaryInsert(source, target, compareFields('foo'));

console.log({ expect, result });

However, I am receiving an empty array as a result. Can anyone help me identify where I might be going wrong?

Answer №1

Your code has been found to contain three errors:

Misuse of Array.splice function

Please refer to the Array.splice documentation for correct usage.

Return value

An array containing the deleted elements.

  • If only one element is removed, an array of one element is returned.
  • If no elements are removed, an empty array is returned.

Errors in binary search implementation

  • If 'first' is greater than 'last', you incorrectly return -1.

Issues with handling negative index from binary search

  • You are passing a negative index to slice as the starting point.
  • According to the documentation (parameters: start):

If the start index is negative, it will begin that many elements from the end of the array.

  • You are inserting the target item one position before the end.
  • However, this turns out to be the correct position in your test case. The test is passing successfully :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue deploying serverless: Module '/Users/.../--max-old-space-size=2048' not found

Everything is running smoothly on my serverless project locally when I use sls offline start. However, when I attempt to deploy it through the command line with serverless deploy, I encounter the following error stack. internal/modules/cjs/loader.js:1030 ...

utilizing a Bootstrap modal element throughout multiple HTML documents

I have a bootstrap modal dialog div that I want to use in all 4 html pages of my web application without repeating the code. I have a common JavaScript file for this purpose. What is the best way to achieve this? <!-- Modal --> <div class="modal ...

When calling UIComponent.getRouterFor, a TypeScript error is displayed indicating the unsafe return of a value typed as 'any'

I have recently integrated TypeScript into my SAPUI5 project and am encountering issues with the ESLint messages related to types. Consider this simple example: https://i.sstatic.net/iorJ5.png In this snippet of code, I am getting an error message saying ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

What is the reason that this jQuery code is exclusive to Firefox?

I am currently working on a code snippet that enables users to navigate back and forth between images by displaying them in a lightbox at full size. The code functions flawlessly in Firefox, however, it does not seem to have any effect on IE, Chrome, and S ...

Determine the status of a script in PHP by incorporating AJAX

I am having trouble with my file upload page in the application. I want to display "Uploading" while the file is uploading and then show "Processing" while the file is being processed. Eventually, after the script completes, my page should redirect to a sp ...

Enable or disable dropdown based on selected radio button status

I need the dropdown to be disabled unless the radio button labeled prov is selected. It should only be enabled when prov is chosen. I attempted to create a demo, but it's not functioning correctly and I can't figure out why. HTML: <td colsp ...

Is it possible to send arguments to the functions executed by "jQuery then"?

Check out the complete code here: http://jsfiddle.net/BurFz/ http://jsbin.com/dagequha/1/edit?js,console /** * executed function chain */ func1('arg1').then(func2).then(func3).then(function () { console.log('execution comp ...

Generating a UTC timestamp in TypeScript

I am currently facing an issue with my application where I need to ensure that it always uses UTC time, regardless of the system time. I have a method in place to create a date: public static createDate(date: Date = new Date()): Date { return new Dat ...

Use JavaScript to convert only the initial letter to uppercase

Once again, I am in the process of learning! Apologies for the simple questions, but learning is key... Attempting to implement a trick I found online to change all letters to uppercase, I am now trying to adjust it to only capitalize the first letters. T ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

The CSS class names for Next.js have not been defined yet

Just getting started with next js and trying to use css modules for styling my nav component. However, I noticed that the classname I setup for the nav element is not showing up in the rendered DOM. Even though I can see the generated styles by webpack in ...

Boxes that change and adapt to the user's input

Need guidance on a tricky problem! I am working on a form to input various cities that the user wants to visit. The form currently consists of one form box and a submit button. My goal is to allow the user to enter multiple cities by clicking an "Add 1 ...

How does React-router handle component reloading when there is a change in the state of the parent component

Within my React application, I've integrated a ResponsiveDrawer component sourced from material-ui's demo. This component essentially displays a drawer containing a list of menu items, a title bar, and a content frame. The state of the component ...

Remove the list by conducting a comparison analysis

<html> <head> <title> Manipulating List Items Using JavaScript </title> <script type="text/javascript"> function appendNewNode(){ if(!document.getElementById) return; var newlisttext = document.changeform.newlist.val ...

Show a dynamic highchart graph displaying linear data retrieved from the database

I am attempting to present data retrieved from a database in a linear highchart format. Here is the JSON response from my database: [{"protocol":"tcp","date":"01/02/20","time":"00:10:20","total":281}, {"protocol":"udp","date":"01/02/20","time":"00:10:30", ...

The functionality of the Drawer component in material-ui v1.0 seems to be incompatible with TypeScript

Every time I try to utilize Drawer from [email protected] using typescript, I encounter the following error: TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Re ...

Storing sound recordings with GridFS

I am currently facing an issue with the following code, it is only working partially and I require assistance in fixing it. The function saveAudioToGridFS() should return a file ID to its calling function. Despite verifying that the value to be returned ...

Tips for altering promises within nested for loops?

Presented below is a complex function that aims to extract model variants from a csv file, which are stored as strings in an array. The path of this csv file depends on information obtained from other csv files, hence the need for looping. The csvService. ...

What is the best way to isolate particular components of an argument and store them in separate variables?

Currently, I am facing a challenge in extracting the name and id of an emoji from a discord argument using discord.js. The input provided to me is <:hack_wump:670702611627769876>, and my goal is to retrieve var id = '670702611627769876' alo ...