Categories
JavaScript Answers

How to Convert Negative Numbers to a Binary String in JavaScript?

To convert negative numbers to a binary string in JavaScript, we can use the toString method or a zero-fill right shift to convert negative numbers to binary strings.

For instance, we can write:

const str = (-3).toString(2);  
console.log(str)

to convert -3 to '-11' .

The negative sign is preserved with this conversion.

To use the bit shift operation to convert a negative number to a binary string, we write:

const str = (-3 >>> 0).toString(2);  
console.log(str)

Then str is '11111111111111111111111111111101' , which is the unsigned 32-bit integer version of the decimal number -3.

Categories
JavaScript Answers

How to Insert a Space Before Each Capital Letter with JavaScript?

To insert a space before each capital letter with JavaScript, we can use a regex to grab each capital letter and add a space before each one with the replace method

For instance, we can write:

const str = "MySites"
const newStr = str.replace(/([A-Z])/g, ' $1').trim()
console.log(newStr)

We call replace on the string str with /([A-Z])/g to get all capital letters from the string.

The g flag matches all capital letters.

Then we pass in ' $1' as the second argument to add a space before each match.

Finally, we call trim to trim off any leading and trailing whitespaces.

Categories
JavaScript Answers

How to Change the Order of HTML Elements with JavaScript?

To change the order of HTML elements with JavaScript, we can use some native JavaScript DOM manipulation functions.

For instance, if we have the following HTML:

<ul>
  <li>Dogs</li>
  <li>Snakes</li>
  <li>Cats</li>
  <li>Bugs</li>
</ul>

We can sort the li elements in alphabetical order with:

const reorder = () => {
  const frag = document.createDocumentFragment();
  const list = document.querySelector("ul");
  const items = list.querySelectorAll("li");
  const sortedList = [...items].sort((a, b) => {
    const c = a.textContent,
      d = b.textContent;
    return c < d ? -1 : c > d ? 1 : 0;
  });
  for (const item of sortedList) {
    frag.appendChild(item);
  }
  list.appendChild(frag);
}

reorder()

We create the reorder function to reorder the elements.

To do this, we create a new document fragment to hold the new content with document.createDocumentFragment .

Then we select all the li elements in the list with:

const list = document.querySelector("ul");
const items = list.querySelectorAll("li");

Next, we sort all the items by their text content value with:

const sortedList = [...items].sort((a, b) => {
  const c = a.textContent,
    d = b.textContent;
  return c < d ? -1 : c > d ? 1 : 0;
});

Then we add the sorted items into the fragment with:

for (const item of sortedList) {
  frag.appendChild(item);
}

Finally, we append the fragment into the list with:

list.appendChild(frag);
Categories
JavaScript Answers

How to Calculate a Person’s Age from Someone’s Birthday with JavaScript?

To calculate a person’s age from someone’s birthday with JavaScript, we can use native JavaScript date methods.

For instance, we can write:

const getAge = (d1, d2 = new Date()) => {
  const diff = d2.getTime() - d1.getTime();
  return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}

console.log(getAge(new Date(1988, 10, 3)));

We create the getAge function that takes 2 dates d1 and d2 .

Then we subtract the timestamps of them that we got with getTime with:

const diff = d2.getTime() - d1.getTime();

And then we divide diff with 1000 * 60 * 60 * 24 * 365.25 to convert diff to the number of years differences, which is the person’s age.

Therefore, the console log should log 32.

Categories
JavaScript Answers

How to Get the Current Time in Nanoseconds Using JavaScript?

To get the current time in nanoseconds using JavaScript, we can use the window.performance.now method and window.performance.timing.navigationStart properties.

For instance, we can write:

const ms = window.performance.timing.navigationStart + window.performance.now()  
const ns = ms / 0.001  
console.log(ns)

to get the current timestamp in nanoseconds.

window.performance.timing.navigationStart returns the timestamp in milliseconds when we run the code.

And window.performance.now returns the number of nanoseconds since the code has run.

Then to convert the timestamp in milliseconds to nanoseconds, we divide ms by 0.001.