When displaying list data, one can iterate through the items using v-for. I have some filter controls which increase or decrease the number of visible items (size, type, name - stuff like that).
Regardless of this, I'd like to limit the amount visible on page to, say, 10 items.
In other words, if the filter hides 50 out of 100 result items (which are still stored in Vuex) I still want to be able to paginate through 5 pages (10 at a time only).
There's a few plugins such as this one which seem to help with that.
However, I'd like to try to do it manually to understand how it's done, though I'm a bit stumped.
Since you have Vuex on board, a getter seems easiest.
export const getters = {
pagedItems: state => {
return pageNo => {
const pageSize = state.pageSize || 10
const items = state.items || []
return items.slice(pageNo * pageSize, pageSize)
}
}
}
Default values (e.g state.items || []) are there to stop the calculation erroring before initial load completes.
Use it on the component in a computed property, which will make it reactive when pageNo changes,
computed: {
pagedItems() {
return this.$store.getters['pagedItems'](this.pageNo)
},
},
It just occurred to me that if you are filtering, you probably want to apply that before the pagination otherwise the display may not be be consistent in size (e.g page 1 filters to 4 items, page 2 to 6 items).
Depends on your exact filter, should be easy to add a getter for filteredItems and use that as source for pagedItems.
well, i would just divide the number of items by the number of data i want to display per page with the rest operator and create number of pages + 1, of course with some validations to empty data and so on.
Imagine you recieve an object that contains lists, this lists represent all the arrays with your data, each array is a row.
Just get the length, divide it with module operator and add one more, in your case, if you have 52 items, and want to have 10 per page:
52 % 10 = 2
52 / 10 = 5
you need 5 pages + 1 for the 2 items.
so i would do something like this:
const NUMBER_ITEMS_PER_PAGE = 10;
const numberItems = list.length;
const pages = numberItems / NUMBER_ITEMS_PER_PAGE
if(numberItems % NUMBER_ITEMS_PER_PAGE > 0) {
pages++;
}
function buildPages(numberPages) {
const pageObj = {}
for(var i = 0; i < pages; i++) {
pageObj.page[i+1]
const arr = []
for(var j = 0; j < (NUMBER_ITEMS_PER_PAGE) * (i + 1); j++) {
arr.push(lists[i])
}
pageObj.page[i+1] = arr;
}
}
of course this is just one possible solution, but i think this can let you start in some way, the code is just to help. good luck
Related
Consider the following scenario:
One million clients visit a store and pay an amount of money using their credit card. The credit card codes are generated using a 16-digit number, and replacing 4 of its digits (randomly) with the characters 'A', 'B', 'C', 'D'. The 16-digit number is generated randomly once, and is used for every credit card, the only change between cards being the positions in the string of the aforementioned characters (that's ~40k possible distinct codes).
I have to organize the clients in a hash table, using a hash function of my choosing and also using open addressing (linear probing) to deal with the collisions. Once organized in the table, I have to find the client who
paid the most money during his purchases.
visited the store the most times.
My implementation of the hash table is as follows, and seems to be working correctly for the test of 1000 clients. However once I increase the number of clients to 10000 the page never finishes loading. This is a big issue since the total number of "shopping sessions" has to be one million, and I am not even getting close to that number.
class HashTable{
constructor(size){
this.size = size;
this.items = new Array(this.size);
this.collisions = 0;
}
put(k, v){
let hash = polynomial_evaluation(k);
//evaluating the index to the array
//using modulus a prime number (size of the array)
//This works well as long as the numbers are uniformly
//distributed and sparse.
let index = hash%this.size;
//if the array position is empty
//then fill it with the value v.
if(!this.items[index]){
this.items[index] = v;
}
//if not, search for the next available position
//and fill that with value v.
//if the card already is in the array,
//update the amount paid.
//also increment the collisions variable.
else{
this.collisions++;
let i=1, found = false;
//while the array at index is full
//check whether the card is the same,
//and if not then calculate the new index.
while(this.items[index]){
if(this.items[index] == v){
this.items[index].increaseAmount(v.getAmount());
found = true;
break;
}
index = (hash+i)%this.size;
i++;
}
if(!found){
this.items[index] = v;
}
found = false;
}
return index;
}
get(k){
let hash = polynomial_evaluation(k);
let index = hash%this.size, i=1;
while(this.items[index] != null){
if(this.items[index].getKey() == k){
return this.items[index];
}
else{
index = (hash+i)%this.size;
i++;
}
}
return null;
}
findBiggestSpender(){
let max = {getAmount: function () {
return 0;
}};
for(let item of this.items){
//checking whether the specific item is a client
//since many of the items will be null
if(item instanceof Client){
if(item.getAmount() > max.getAmount()){
max = item;
}
}
}
return max;
}
findMostFrequentBuyer(){
let max = {getTimes: function () {
return 0;
}};
for(let item of this.items){
//checking whether the specific item is a client
//since many of the items will be null
if(item instanceof Client){
if(item.getTimes() > max.getTimes()){
max = item;
}
}
}
return max;
}
}
To key I use to calculate the index to the array is a list of 4 integers ranging from 0 to 15, denoting the positions of 'A', 'B', 'C', 'D' in the string
Here's the hash function I am using:
function polynomial_evaluation(key, a=33){
//evaluates the expression:
// x1*a^(d-1) + x2*a^(d-2) + ... + xd
//for a given key in the form of a tuple (x1,x2,...,xd)
//and for a nonzero constant "a".
//for the evaluation of the expression horner's rule is used:
// x_d + a*(x_(d-1) + a(x_(d-2) + .... + a*(x_3 + a*(x_2 + a*x1))... ))
//defining a new key with the elements of the
//old times 2,3,4 or 5 depending on the position
//this helps for "spreading" the values of the keys
let nKey = [key[0]*2, key[1]*3, key[2]*4, key[3]*5];
let sum=0;
for(let i=0; i<nKey.length; i++){
sum*=a;
sum+=nKey[i];
}
return sum;
}
The values corresponding to the keys generated by the hash function are instances of a Client class which contains the fields amount (the amount of money paid), times (the times this particular client shopped), key (the array of 4 integers mentioned above), as well as getter functions for those fields. In addition there's a method that increases the amount when the same client appears more than once.
The size of the hash table is 87383 (a prime number) and the code in my main file looks like this:
//initializing the clients array
let clients = createClients(10000);
//creating a new hash table
let ht = new HashTable(N);
for(let client of clients){
ht.put(client.getKey(), client);
}
This keeps running until google chrome gives a "page not responding" error. Is there any way I can make this faster? Is my approach on the subject (perhaps even my choice of language) correct?
Thanks in advance.
The page is not responding since the main (UI) thread is locked. Use a WebWorker or ServiceWorker to handle the calculations, and post them as messages to the main thread.
Regarding optimizing your code, one thing I see is in findBiggestSpender. I'll break it down line-by-line.
let max = {getAmount: function () {
return 0;
}};
This is a waste. Just assign a local variable, no need to keep calling max.getAmount() in every iteration.
for(let item of this.items){
The fastest way to iterate a list in Javascript is with a cached length for loop: for (let item, len = this.items.length; i < len; i ++)
if(item instanceof Client){
This is slower than a hard null check, just use item !== null.
I will try to be specific as possible as I can't find anything on this through the Google gods.
I have a list of 10 movies. I would like to display the movies in pairs. The user picks their favorite of the two. The next pair is displayed. The user picks their favorite of those two, so on and so on until I can faithfully output the list in their order of preference from 1-10.
I'm doing this in Javascript, but even just a way to do it that is language agnostic would be great. No need to worry about syntax or UI stuff.
With three movies it's pretty easy (initial order of movies and order of pairs shouldn't matter):
1.sw
2.esb
3.rotj
example 1
1vs2: winner = 2
2vs3: winner = 2
1vs3: winner = 1
Sorted List: 2,1,3
example 2
1vs3: winner = 1
1vs2: winner = 2
2vs3: winner = 2
Sorted List: 2,1,3
First time posting so if I need to be more specific, need to have exact syntax, etc., please don't hesitate to let me know.
The minimum number of comparisons required to sort 10 items is 22. (See https://oeis.org/A036604). Do you really think your users will suffer through 22 "which movie do you like better?" questions? And do you honestly believe that the result will be useful? You'll have many cases where a user will say that he liked movie A better than B, and B better than C, but he liked movie C better than he liked movie A. So now you have the problem that:
A > B
B > C
C > A
And there's no reasonable way to resolve that conflict.
In short, your user interface is flawed. You can try to build it, but your users won't like it and your results will not be reliable.
A better interface would be to list the 10 movies and allow the users to arrange them in order of preference. Or let the user rate the movies on a scale from 1 to 5. But expecting users to answer 22 questions and get a complete ordering is a fool's errand.
The basic problem is easy. We have a ton of sorting algorithms that will work with O(n log(n)) comparisons. For instance mergesort:
// Split the array into halves and merge them recursively
function mergeSort (arr) {
if (arr.length === 1) {
// return once we hit an array with a single item
return arr
}
const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down
const left = arr.slice(0, middle) // items on the left side
const right = arr.slice(middle) // items on the right side
return merge(
mergeSort(left),
mergeSort(right)
)
}
// compare the arrays item by item and return the concatenated result
function merge (left, right) {
let result = []
let indexLeft = 0
let indexRight = 0
while (indexLeft < left.length && indexRight < right.length) {
if (left[indexLeft] < right[indexRight]) {
result.push(left[indexLeft])
indexLeft++
} else {
result.push(right[indexRight])
indexRight++
}
}
return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight))
}
So in principle you need to simply replace left[indexLeft] < right[indexRight] with an arbitrary comparison function that asks the user, gets an answer, and then continues.
Now there is a catch. The catch is that you need to make this code asynchronous. When you go to ask the user, you need to ask the user, then return to inside your code. If you're using node at the console, then you can do this with async/await. If you are not, then you'll need to figure out how to do it with promises. Modifying mergeSort is easy, just make the end into:
return Promise.all([mergeSort(left), mergeSort(right)]
).then(function (values) {return merge(values[0], values[1])});
The trick is in turning the loop inside of merge into a function that takes the current state of your iteration, and returns a promise that asks the question, then either returns the final sorted array, or returns a promise that handles the next iteration.
Since this looks like homework, whose whole purpose is to make you face that mental challenge, I'll leave my answer off here. Fair warning, I gave you a hint about how to do it, but if you're just learning about async code your head is SUPPOSED to spin as you figure it out.
To determine all possible combinations from your array try the following loop. Assuming order does not matter and we do not want repeats:
var arr = [1,2,3,4,5,6,7,8,9,10]
var arr_count = arr.length
var combinations_array = []
for (i = 0; i < arr_count; i++) {
var combinations = arr_count - (i+1)
for (y = 0; y < combinations; y++) {
combination = [arr[i],arr[(combinations - y)]];
combinations_array.push(combination);
}
}
In your example I'd pass Movie ID's into arr then iterate through the combinations_array to determine which combination of movies should be displayed next.
To produce a list of pairs, I would use a nested loop like this:
var items = [1,2,3,4,5,6,7,8,9,10],
result = [],
x = 0,
y = 0;
for (x = items.length; x--;)
{
for(y = x; y--;)
{
result.push({ a: items[x], b: items[y] });
}
}
console.debug(result);
The second loop is initialised from the outer loops incrementor so that you don't end up with duplicates.
Once you have the pairs, you should be able to build the ui from that.
Hope it helps!
I am relatively new to programming and am having some issues with a project I am working on.
msg.newCG2 = [];
for(i=0;i<msg.newCG.length;i++){
for(j=0;j<msg.campaignGroup.length;i++){
if(msg.campaignGroup[j].col10 === msg.newCG[j]){
msg.groupTotals = msg.groupTotals + msg.campaignGroup[j].col11;
}
msg.newCG2.push(msg.newCG[i], msg.groupTotals)
}
}
Basically, for each one of the "IDs" (integers) in msg.newCG, I want to look for each ID in msg.campaignGroup and sum up the totals for all listings with the same ID, from msg.campaignGroup.col11 - then push the ID and the totals to a new array - msg.newCG2.
When I run the code, the first item sent through processes, but grinds to a halt because of memory. I assume this is because of an error in my code.
Where did this code go wrong? I am sure that there are better ways to do this as a whole, but I am curious where I went wrong.
There is a typo in your second for loop and the push needs to happen inside the outer loop.
msg.newCG2 = [];
for(i=0;i<msg.newCG.length;i++){
for(j=0;j<msg.campaignGroup.length;j++){
if(msg.campaignGroup[j].col10 === msg.newCG[i]){
msg.groupTotals = msg.groupTotals + msg.campaignGroup[j].col11;
}
}
msg.newCG2.push(msg.newCG[i], msg.groupTotals)
}
How about:
msg.newCG2 = [];
for (i=0; i < msg.newCG.length; i++) {
var groupTotal = 0;
for (j=0; j < msg.campaignGroup.length; j++) {
if (msg.campaignGroup[j].col10 === msg.newCG[i]){
groupTotal = groupTotal + msg.campaignGroup[j].col11
}
}
msg.newCG2.push(groupTotal)
}
Rather than looping 1.2M times, it would be more efficient to use a single-pass over the 4000 campaign groups, grouping by id to create an array of totals for all ids -- I like using the reduce() function for this:
var cgMap = msg.campaignGroups.reduce(function(arr, grp) {
var grpid = grp.col10;
var count = grp.col11;
var total = arr[grpid] || 0;
arr[grpid] = total + count;
},
[]);
I know, the reduce(...) function is not the easiest to grok, but it takes the second arg (the empty array) and passes it, along with each campaign group object in turn, to that inline function. The result should be a simple array of group totals (from col11), indexed by the group id (from col10).
Now, it's just a matter of returning the totals for those 300 ids found in msg.newCG -- and this map() function does that for us:
var cgOut = msg.newCG.map(function(gid) {
return cgMap[gid]; // lookup the total by group id
}
);
I've made some assumptions here, like the group ids are not terribly large integers, and are rather closely spaced (not too sparse). From the original code, I was not able to determine the format of the data you are wanting to return in msg.newCG2. The final push() function would append 2 integers onto the array -- the output group id and the total for that group. Having pairs of group ids and totals interleaved in a flat array is not a very useful data structure. Perhaps you meant to place the total value into an array, indexed by the group id? If so, you could re-write that line as:
msg.newCG2[msg.newCG[i]] = msg.groupTotals;
So I'm learning react and js, and I'm trying to loop every 20 (the limit in a single page) and show this pictures, also show in the bottom this pages index using bootstrap. but it not really working this is my code:
const pictureItems = this.state.imgFiles.map((img, index) => {
return (
<PictureListItem
id={index}
key={`img-${img.name}`}
imgFile={img}
pictureDataUpdate={this.onUpdatePicture}
/>
);
});
const pageNumber = this.state.imgFiles.length / 20;
let pages = "";
for (let i = 0; i < pageNumber; i++) {
pages += <li><a>{i}</a></li>;
return pages;
}
I was thinking may be I can pass the value of the index to the loop and multiply by 20 for the start and then add 20 to the end. but I can't even get the pages to show well.
protip: don't do yourself what the language already does on its own.
const picturesPerPage = 20;
const images = this.state.imgFiles;
...
// get the current page, rounded down. We don't want fractions
let currentPageNumber = (images.length / picturesPerPage)|0;
// find the start and end position in the "images" array for this page
let start = currentPageNumber * picturesPerPage;
let end = (1+currentPageNumber) * picturesPerPage;
// cool: make JS get those items for us, and then map those items to bits of JSX
let pages = images.slice(start, end).map(img => {
return (
<li key={img.src}>
<a href={img.href}>
<img src={img.src} alt={img.alt}/>
</a>
</li>
);
});
// and we're done.
return <ul>{ pages }</ul>;
Note that if you're building an array of on-the-fly React elements, they need to have a key attribute so that the React diff engine can properly do its job - the key needs to uniquely identify the actual thing, so you can't use array position (['a','b'] and ['b','a'] are the same array, but if you pretend the array position is a key, rather than "just swap the two elements" you're lying about what happens going from one to the other, claiming actual content changes occurred when they didn't, and things get horribly inefficient).
Also note that you tried to use += for adding elements into an array - that is illegal syntax, += is string concatenation. To add individual elements to an array you use array.push (or if you need to so something weird, array.splice)
I have a list of items and a comparison function f(item1, item2) which returns a boolean.
I want to generate groups out of these items so that all items in a same group satisfy the condition f(itemi, itemj) === true.
An item can be included in several groups. There is no mimimum size for a group.
I am trying to write an efficient algorithm in javascript (or other language) for that. I thought it would be pretty easy but I am still on it after a day or so...
Any pointer would be highly appreciated!
(the max size of my items array is 1000, if it helps)
OK, so here's how I did it in the end. I am still unsure this is completely correct but it gives good results so far.
There are two phases, first one is about creating groups that match the condition. Second one is about removing any duplicates or contained groups.
Here's the code for the first part, second part if quite trivial:
for(index = 0; index < products.length; index++) {
existingGroups = [];
seedProduct = products[index];
for(secondIndex = index + 1; secondIndex < products.length; secondIndex++) {
candidateProduct = products[secondIndex];
if(biCondition(seedProduct, candidateProduct)) {
groupFound = false;
existingGroups.forEach(function(existingGroup) {
// check if product belongs to this group
isPartOfGroup = true;
existingGroup.forEach(function(product) {
isPartOfGroup = isPartOfGroup && biCondition(product, candidateProduct);
});
if(isPartOfGroup) {
existingGroup.push(candidateProduct);
groupFound = true;
}
});
if(!groupFound) {
existingGroups.push([candidateProduct]);
}
}
}
// add the product to the groups
existingGroups.forEach(function(group) {
group.push(seedProduct);
if(group.length > minSize) {
groups.push(group);
}
});
}
Instead of items I use products, which is my real use case.
The bicondition tests for f(item1, item2) && f(item2, item1). To speed up and avoid duplication of calculus, I created a matrix of all condition results and I use this matrix in the biCondition function.