0

I am new to java script.

I have an array with the first 10000 values for factorials, in the form of strings. (1-10000). I have it in an array as part of a function.

<!DOCTYPE html>
<html>
<body>
<p>Provide input number, then click on accept. Textbiox value will change to appropriate value.</p>
Name: <input type="text" id="myText" value="Mickey">

<button onclick="myFunction()">accept</button>

<script>
function myFunction() {
var values = ["1",
"2",
"6",
"24",
"120",
"720",
"5040",
"40320",
"362880",
"3628800",
"39916800",...

Now, it takes about 20 seconds to load that website, I wanted to know how I can speed that up.

Lazy loading is the feature I am after, but all of them are sequences/functions that generate array values on the go, or image arrays, loading images from somewhere else.

How can I apply lazy loading to a static array? thank you.

1 Answer 1

2

I'd generate the values when requested instead. If you're worried about performance, you can make a cache so as not to re-calculate values already found.

const factorials = new Map();
document.querySelector('button').addEventListener('click', () => {
  const val = Number(document.querySelector('#myText').value);
  if (!val || !Number.isInteger(val) || val < 0) return console.log('bad input...');
  console.log(String(getFactorial(BigInt(val))));
});
const getFactorial = (n) => {
  if (factorials.has(n)) return factorials.get(n);
  if (n === 1n) return 1n;
  const fact = getFactorial(n - 1n) * n;
  factorials.set(n, fact);
  return fact;
};
<input type="text" id="myText" value="5">

<button>accept</button>

Sign up to request clarification or add additional context in comments.

4 Comments

What about something as simple as running the script at server? Generally speaking, running at server will significantly speed up the process.
Sure, if one happens to have control over server-side code, that'd be fine too - but calculating up to 9999! is very easy for modern hardware
thank you for the quick reply, I wish to expand this array later on, where a single value will indeed take in the order of minutes to calculate, your solution only works while the number of values is small. Is there a way to implement lazy loading for a static array?
@Barny If you cannot calculate it on the client, and if the payload data would be too large to send in the initial HTML response, putting it on the server is the right way to go. Put the list on the server, and when the user clicks, make a request and have the server send them the associated result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.