I am new to JavaScript, I want to get the right page count.
if one page the item count is 20, and the page count is 23, the page should be 2.
var count = 23
var per_page_count = 20
If in other language we can use:
count / per_page_count + 1
to get the page count, but in JavaScript we can not get it.
I also tried use Math.round, still not work
console.log(Math.round(count/per_page_count)) // there I want to get 2, but get 1
You can use
Math.ceil(count/per_page_count)
The Math.ceil() function returns the smallest integer greater than or equal to a given number.
from Math.ceil document.
I think you are trying to implement some sort of pagination. So I would suggest :
Maths.ceil(count/per_page_count)
Related
since lunr already build the index,
I want get first 10 record (page 1) base on whatever search result (search what can I get the whole dataset as result?)
second, I want get page 2, 10 record, offset=10, (starting from 11, next 10 record)
and so on.
So far, look like lunr only can search keywords. No pagination build in.
I have a way to work around it.
idx.search('')
or
idx.search(' ')
or
idx.search(' ')
search empty, or space, or 2 space, you will get all dataset as result.
For page 1: you search idx.search('') to get all dataset as result. Now you use for loop through, only get 1 to 10 records,then break for loop.
For page 2: you perform same idx.search('') search again, you should get the same result set as last time, but you this time you use for loop, from 11 to 20. Because offset is 10(you skip first 10).
and so on
For page x: you perform same idx.search('') search again, you should get the same result set as last time, but this time you use for loop, from (x * 10+1) to ((x * 10+1) +10). Because offset is x * 10 (you skip first x * 10).
I am trying to understand how to approach math problems such as the following excerpt, which was demonstrated in a pagination section of a tutorial I was following.
const renderResults = (arrayOfItems, pageNum = 1, resultsPerPage = 10) => {
const start = (pageNum - 1) * resultsPerPage;
const end = pageNum * resultsPerPage;
arrayOfItems.splice(start, end).forEach(renderToScreenFunction);
};
In the tutorial this solution was just typed out and not explained, which got me thinking, had I not seen the solution, I would not have been able to think of it in such a way.
I understood the goal of the problem, and how splice works to break the array into parts. But it was not obvious to me how to obtain the start and end values for using the splice method on an array of of indefinite length. How should have I gone about thinking to solve this problem?
Please understand, I am learning programming in my spare time and what might seem simple to most, I have always been afraid and struggle with math and I am posting this question in hopes to get better.
I would really appreciate if anyone could explain how does one go about solving such problems in theory. And what area of mathematics/programming should I study to get better at such problems. Any pointers would be a huge help. Many thanks.
OK, so what you're starting with is
a list of things to display that's, well, it's as long as it is.
a page number, such that the first page is page 1
a page size (number of items per page)
So to know which elements in the list to show, you need to think about what the page number and page size say about how many elements you have to skip. If you're on page 1, you don't need to skip any elements. What if you're on page 5?
Well, the first page skips nothing. The second page will have to skip the number of elements per page. The third page will have to skip twice the number of elements per page, and so on. We can generalize that and see that for page p, you need to skip p - 1 times the number of elements per page. Thus for page 5 you need to skip 4 times the number of elements per page.
To show that page after skipping over the previous pages is easy: just show the next elements-per-page elements.
Note that there are two details that the code you posted does not appear to address. These details are:
What if the actual length of the list is not evenly divisible by the page size?
What if a page far beyond the actual length of the list is requested?
For the first detail, you just need to test for that situation after you've figured out how far to skip forward.
Your function has an error, in the Splice method
arrayOfItems.splice(start, end).forEach(renderToScreenFunction);
The second argument must be the length to extract, not the final
index. You don't need to calculate the end index, but use the
resultsPerPage instead.
I've rewrite the code without errors, removing the function wrapper for better understanding, and adding some comments...
// set the initial variables
const arrayOfItems =['a','b','c','d','e','f','g','h','i','j','k','l','m'];
const pageNum = 2;
const resultsPerPage = 5;
// calculate start index
const start = (pageNum - 1) * resultsPerPage; // (2-1)*5=5
// generate a new array with elements from arrayOfItems from index 5 to 10
const itemsToShow = arrayOfItems.splice(start, resultsPerPage) ;
// done! output the results iterating the resulting array
itemsToShow.forEach( x=> console.log(x) )
Code explanation :
Sets the initial parameters
Calculate the start index of the array, corresponding to the page you try to get. ( (pageNum - 1) * resultsPerPage )
Generates a new array, extracting resultsPerPage items from arrayOfItems , starting in the start index (empty array is returned if the page does not exist)
Iterates the generated array (itemsToShow) to output the results.
The best way to understand code, is sometimes try to run it and observe the behavior and results.
I need to calculate the percentile rank of a particular value against a large number of values filtered in various different ways. The data is all stored on Parse.com, which has a limitation of returning a maximum of 1000 rows per query. The number of values stored is likely to exceed well over 100,000.
By 'percentile rank', I mean I need to calculate the percentage of values that the provided value is greater than. I am not trying to calculate the value of a provided percentile. For example, given a list of values {20, 23, 24, 29, 30, 31, 35, 40, 40, 43} the percentile rank of the provided value 35 is 70%. The algorithm for this is simply the rank of the value / count of values * 100. Not sure if 'percentile rank' is the correct terminology for this.
I have considered a couple of different approaches to this. The first is to pull down the full list of values (into Parse Cloud) and then calculate the percentile rank from there, then filter the list and calculate again, repeating the last two steps as many times as required. The problem with this approach is it will not work once we reach 1000 values, which we can expect pretty quickly.
Another option, which is the best I can come up with so far, is to query the count of items, and the rank of the provided value. For example:
var rank_world_alltime = new Parse.Query("Values")
.lessThan("value", request.params.value) // Filters query to values less than the provided value, so counting this query will return the rank
.count();
var count_world_alltime = new Parse.Query("Values")
.count();
Parse.Promise.when(rank_world_alltime, count_world_alltime).then(function(rank, count) {
percentile = rank / count * 100;
console.log("world_alltime_percentile = " + percentile);
});
This works well for a single calculation, but I need to perform multiple calculations, and this approach very quickly becomes a lot of queries. I expect to need to run about 15 calculations per call, which is 30 queries. All calculations need to complete in under 3 seconds before Parse terminates the job, and I am limited to 30 reqs/second, so this is very quickly going to become a problem.
Does anyone have any suggestions on how else I could approach this? I've thought about somehow pre-processing some of this but can't quite work out how to do so, as the filters will be based on time and location (city and country), so there are potentially a LOT of pre-calculations that will need to be run at regular intervals. The results do not need to be 100% accurate but something close.
I don't know much about parse, but as far as I understand what you say, it is some kind of cloud database thingy that holds your hiscores, and limits you 1000 rows per query, 3 seconds per job, and 30 queries per second.
In order to have approximate calculations and divide by 2 the number of queries, I would first of all cache the total (count_world_alltime, count_region,week, whatever). If you can save them somewhere locally. For numbers of 100K just getting the order of magnitude (thus not the latest updated number) should be good enough to get a percentile.
Maybe you can get several counts per query. However my lack of expertise in parse/nosql kind of stops me from being sure of this, you'll have to check their documentation. If it is possible however, for the case where you need percentiles for a serie of values all in the same category, I would
Order the values, let's call them a,b,c,d,e (once ordered)
Get the number of values between the intervals [0,a] [a,b] [b,c] [c,d] [d,e]
Use the cached total to get the percentiles (where Nxy is the number of values in [x,y]) :
Pa = 100 * N0a / total
Pb = 100 * ( N0a + Nab ) / total
Pc = 100 * ( N0a + Nab + Nbc ) / total
and so on...
If you need a value ranked worldwide, the other per region, some per week others over all times, etc, this doesn't apply. In that case I don't think you can get below 1 query/number, with caching the totals.
I just cannot figure this out, nor find any kind of similar question that makes any sense to me. My problem: I am extracting records from a database and displaying them in multiples of 12 per panel on my web page. I therefore need to know how many panels to display all records, using JavaScript (or possibly JQuery). Example:
records = 27;
panels = records / 12; //(which is 2.25)
Obviously I will need 3 panels to display all 27 records, but how can I get that from the result of 2.25? I've tried also using % instead of / but somehow I'm just not getting it.
records = 27; panels = Math.ceil(records / 12); // 3
Round up.
if result is not fully divisible by 12, then use Math.ceil (2.25) which equals 3
Is there a simple jQuery way to create numbers randomly showing then a number 1 -6 is choosing after a few seconds? [Like dice]
This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:
var number = 1 + Math.floor(Math.random() * 6);
Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
$('#my_div').text(number);
},
1000); // every 1 second
You don't need jQuery, just use javascript's Math.random function.
edit:
If you want to have a number from 1 to 6 show randomly every second, you can do something like this:
<span id="number"></span>
<script language="javascript">
function generate() {
$('#number').text(Math.floor(Math.random() * 6) + 1);
}
setInterval(generate, 1000);
</script>
function rollDice(){
return (Math.floor(Math.random()*6)+1);
}
Javascript has a random() available. Take a look at Math.random().
Coding in Perl, I used the rand() function that generates the number at random and wanted only 1, 2, or 3 to be randomly selected. Due to Perl printing out the number one when doing "1 + " ... so I also did a if else statement that if the number generated zero, run the function again, and it works like a charm.
printing out the results will always give a random number of either 1, 2, or 3.
That is just another idea and sure people will say that is newbie stuff but at the same time, I am a newbie but it works. My issue was when printing out my stuff, it kept spitting out that 1 being used to start at 1 and not zero for indexing.