Categories
JavaScript Answers

How to convert a string to long in JavaScript?

Sometimes, we want to convert a string to long in JavaScript.

In this article, we’ll look at how to convert a string to long in JavaScript.

How to convert a string to long in JavaScript?

To convert a string to long in JavaScript, we can convert it to a bigint.

For instance, we write

const bi = BigInt("1274836528318476135");

to convert the "1274836528318476135" string to a bigint with the BigInt function.

Conclusion

To convert a string to long in JavaScript, we can convert it to a bigint.

Categories
JavaScript Answers

How to update the Context value in a Provider from the Consumer with React?

To update the Context value in a Provider from the Consumer with React, we pass the state setter function from the provider so it can be retrieved by the consumer.

For instance, we create the authContext.js file with

import { createContext } from "react";

const authContext = createContext({
  authenticated: false,
  setAuthenticated: (auth) => {}
});

export default authContext;

We call createContext to create the context with an object with some data we want to share.

Next, in login.js, we write

import React, { useContext } from "react";
import authContext from "./authContext";

export default () => {
  const { setAuthenticated } = useContext(authContext);
  const handleLogin = () => setAuthenticated(true);
  const handleLogout = () => setAuthenticated(false);

  return (
    <React.Fragment>
      <button onClick={handleLogin}>login</button>
      <button onClick={handleLogout}>logout</button>
    </React.Fragment>
  );
};

to call useContext to get the authContext.

And then we call the setAuthenticated function to set the value of authenticated.

Finally, we write

import ReactDOM from "react-dom";
import React, { useState } from "react";

import authContext from "./authContext";
import Login from "./Login";

const App = () => {
  const [authenticated, setAuthenticated] = useState(false);

  return (
    <authContext.Provider value={{ authenticated, setAuthenticated }}>
      <div> user is {`${authenticated ? "" : "not"} authenticated`} </div>
      <Login />
    </authContext.Provider>
  );
};

ReactDOM.render(<App />, document.getElementById("container"));

in index.js to call useState to create the authenticated state.

We pass authenticated and setAuthenticated into the context by setting the value prop of authContext.Provider to an object with authenticated and setAuthenticated.

As a result, we call call it in login.js since we pass the values in the provider.

Categories
JavaScript Answers

How to force a script reload and re-execute with JavaScript?

Sometimes, we want to force a script reload and re-execute with JavaScript.

In this article, we’ll look at how to force a script reload and re-execute with JavaScript.

How to force a script reload and re-execute with JavaScript?

To force a script reload and re-execute with JavaScript, we can make a copy of the original script, remove it, and then append it again.

For instance, we write

const scriptTag = document.createElement("script");
scriptTag.innerText = "document.body.innerHTML += 'Here again ---<br>';";
const head = document.getElementsByTagName("head")[0];
head.appendChild(scriptTag);

setInterval(() => {
  head.removeChild(scriptTag);
  const newScriptTag = document.createElement("script");
  newScriptTag.innerText = scriptTag.innerText;
  head.appendChild(newScriptTag);
  scriptTag = newScriptTag;
}, 1000);

We create the scriptTag with createElement.

And then we set its innerText property to add the script we want to run inside.

Next, we get the head element with getElementsByTagName.

Then we call head.appendChild with scriptTag to append it to the head.

In the setInterval callback, we remove the original scriptTag with head.removeChild.

Then we we recreate the script tag as newScriptTag and append it again to the head with head.appendChild.

Conclusion

To force a script reload and re-execute with JavaScript, we can make a copy of the original script, remove it, and then append it again.

Categories
JavaScript Answers

How to find the time left in a setTimeout() timer with JavaScript?

Sometimes, we want to find the time left in a setTimeout() timer with JavaScript.

In this article, we’ll look at how to find the time left in a setTimeout() timer with JavaScript.

How to find the time left in a setTimeout() timer with JavaScript?

To find the time left in a setTimeout() timer with JavaScript, we can use the timer’s _idleStart and _idleTimeout properties.

For instance, we write

const timeout = setTimeout(() => {}, 3600 * 1000);

const getTimeLeft = (timeout) => {
  return Math.ceil(
    (timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000
  );
};

setInterval(() => {
  console.log("Time left: ", getTimeLeft(timeout), "s");
}, 2000);

to create the timeout timer object with setTimeout.

Then we calculate the time left before running the setTimeout callback with the getTimeLeft function.

In it, we use timeout._idleStart + timeout._idleTimeout - Date.now() to compute the time left before the setTimeout callback is run in milliseconds.

Then we divide the ceiling of the number and divide it by 1000 to get the number of seconds.

Next, we call setInterval with a callback that calls getTimeLeft with timeout in the callback to get the number of seconds left before the setTimeout callback is called every 2 seconds.

Conclusion

To find the time left in a setTimeout() timer with JavaScript, we can use the timer’s _idleStart and _idleTimeout properties.

Categories
JavaScript Answers

How to evaluate a string as a mathematical expression in JavaScript?

Sometimes, we want to evaluate a string as a mathematical expression in JavaScript.

In this article, we’ll look at how to evaluate a string as a mathematical expression in JavaScript.

How to evaluate a string as a mathematical expression in JavaScript?

To evaluate a string as a mathematical expression in JavaScript, we can use the mathjs library.

To install it, we run

npm install mathjs

Then we can use it by writing

import { evaluate } from "mathjs";

const n = evaluate("1.2 * (2 + 4.5)");

to call evaluate with the math expression we want to evaluate.

The return value is the value of the expression after evaluating as a number.

Conclusion

To evaluate a string as a mathematical expression in JavaScript, we can use the mathjs library.