How to get more than 1000 results Parse [duplicate] - javascript

This question already has answers here:
How to retrieve more than 1000 rows from Parse.com?
(11 answers)
Closed 7 years ago.
I have a cloud code which returns sometimes more than 1000 results , I am not getting how to chain query to get more than 1000 results in following code.
var User = Parse.Object.extend("Journal");
var mainQuery = new Parse.Query(User);
mainQuery.equalTo("user",username);
mainQuery.limit(1000);
mainQuery.find({
success: function(results) {
count = 0;
var avg = 0;
console.log("self:"+results.length);
for(j = 0; j < results.length ; j++)
{
var entry = results[j];
if(strcmp1(day,"All") != 0)
{
var dt = entry.get("created");
var weekDay = dt.getDay();
if(weekDay == day)
{
total += entry.get("Level");
count++;
}
}
else
{
total += entry.get("Level");
count++;
}
}
if(count > 1)
avg = total / count;
response.success(avg);
}
});
limit function is used for raising the default limit of 100 which is max 1000 per query result return cycle .

I am using this code presently. This can fetch more than 1000 results.
The values are sorted according to "objectId". You can sort according to "createdAt" by changing accordingly.
Final results are stored in result array
var result = [];
var processCallback = function(res) {
result = result.concat(res);
if (res.length == 1000) {
process(res[res.length-1].id);
return;
}
//To print all the ids
for(var i=0;i<result.length;i++){
console.log(result[i].id);
}
}
var process = function(skip) {
var query = new Parse.Query("ObjectName");
if (skip) {
query.greaterThan("objectId", skip);
}
query.limit(1000);
query.ascending("objectId");
query.find().then(function querySuccess(res) {
processCallback(res);
}, function queryFailed(error) {
});
}
process(false);

Related

How to improve the speed of a for loop

I'm using Datatables and Highcharts for a reporting screen but it is quite slow to load the chart (approx 10 Seconds), using performance.now() I can see the segment below is causing the delay:
Please note, the 'indexes' array contains 6500+ records.
var monthTO = {};
var indexes = TurnoverRepoTable.rows({ search: 'applied' }).indexes().toArray();
for (var i = 0; i < indexes.length; i++) {
var cMonth = TurnoverRepoTable.cell(indexes[i], 2).data();
var value = TurnoverRepoTable.cell(indexes[i], 6).data();
if (monthTO[cMonth] === undefined) {
monthTO[cMonth] = Number(value);
} else {
monthTO[cMonth] = monthTO[cMonth] + Number(value);
}
}
So, I'd like to know if there a more efficient way of achieving this?
Cheers, Chris
Hi,
I have solved this issue by referencing the data directly (not by using the indexes), code below:
var dataset = TurnoverRepoTable.rows({ search: 'applied' }).data().toArray();
// For each row, extract the office and add the salary to the array
for (var i = 0; i < dataset.length; i++) {
var cMonth = dataset[i].job.cMonth
var value = dataset[i].job.estout
if (monthTO[cMonth] === undefined) {
monthTO[cMonth] = Number(value);
} else {
monthTO[cMonth] = monthTO[cMonth] + Number(value);
}
}

Running Loop showing results [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can I use a loop to flip a coin 20 times, each time displaying the result of the flip as a string on the page? After the loop completes, I want to return the array with the result of each flip.
What I have so far:
function display20Flips() {
const results = [];
var i;
var results = '';
for (i = 0; i < 20; i++) {
}
const coin = {
state: 0,
flip: function() {
this.state = Math.floor(Math.random() * 2);
},
toString: function() {
if (this.state === 0) {
return Heads;
} else {
return Tails
}
},
toHTML: function() {
const image = document.createElement('img');
image.src = `$this.toString()}.png`
image.alt = this.toString()
return image;
}
};
function display20Flips() {
const results = [];
// 4. One point: Use a loop to flip the coin 20 times, each time displaying the result of the flip as a string on the page. After your loop completes, return an array with the result of each flip.
for (let i = 0; i < 20; i++) {
if(i%2){
results[i] = 'heads';
} else{
results[i] = 'tails';
}
console.log(results[i])
}
}
display20Flips();
function display20Images() {
const results = [];
// 5. One point: Use a loop to flip the coin 20 times, and display the results of each flip as an image on the page. After your loop completes, return an array with result of each flip.
}
You might want to create a FlipCoin function which determinates the value, call this function in a loop, storing the function result value in a variable, which you can print to screen and add to a results array.
something like this
// Returns 1 or 0, i.e. 1 = Head, 0 = Tail
function flipCoin() {
var flipValue = Math.floor(Math.random() * 100);
return flipValue % 2;
}
function main() {
let results = [];
for (cnt = 0; cnt < 20; cnt++) {
let result = flipCoin();
results.push(result);
console.log(result == 0 ? "Tail" : "Head");
}
console.dir(results);
}
main();
I believe you want something like this:
function display20Flips() {
var results = [];
for (let i = 0; i < 20; i++) {
if(i%2){
results[i] = 'heads';
} else{
results[i] = 'tails';
}
console.log(results[i])
}
}
display20Flips(); // for displaying in snippet code
Use Array(20) to create an array of size 20
Array.map to iterate through each element, use Array.fill to fill the array with null values else it will not iterate through.
Math.random()*10 to generate a random number between 0-10.
If the value is even then returned Head else Tails
function display20Flips() {
return Array(20).fill().map(e => Math.random()*10 & 1 ? 'Head' : 'Tails')
}
console.log(display20Flips())
Im not an expert but here it is :D
<!DOCTYPE html>
<html>
<body>
<script>
var results = [];
function display20Flips() {
for (var i = 0; i <20; i++ ){
var x = Math.floor((Math.random() * 2));
if(x == 0){
results[i] = "heads";
}else{
results[i] = "tails";
}
}
console.log(results);
}
display20Flips();
</script>
</body>
</html>

Javascript program is not recognizing an if statement [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 5 years ago.
The program is running an else statement when I'm expecting an if statement to run. When the program checks the gameObject's playerSelections property against the gameObject's colorSequence property I expect the program to log 'You got it. Way to go!' if the two arrays are equivalent. Instead I keep getting the console log statement 'Better luck next time!'. Does anyone have any ideas as to why this may be happening. `
const $headerText = $('.fly-in-text');
setTimeout(function() {
$headerText.removeClass('temp-hide');
}, 500);
let gameObject = {
colorIds: ['#blue', '#red', '#green', '#yellow'],
currentLevel: 1,
colorSequence: [],
playerSelections: [],
illuminate:function(color){
setTimeout(function(){
$(color).css('opacity', .5);
setTimeout(function() {
$(color).css('opacity', 1);
},500);
},500);
},
levelSequence: function(){
const iterationCount = this.currentLevel + 2;
for (let i = 0; i < iterationCount; i++) {
this.colorSequence.push(this.colorIds[Math.floor(Math.random() * 4)]);
}
this.startGame(this.colorSequence);
},
startGame: function(sequence) {
let i = 0;
const self = this;
var interval = setInterval(function(){
self.illuminate(sequence[i]);
i++;
if (i >= sequence.length){
clearInterval(interval);
}
}, 1000);
}
}
$circle.click(function() {
clearTimeout(interval);
$(this).toggleClass('rotate');
gameObject.levelSequence();
$('.colors').click(function(){
gameObject.playerSelections.push(`#${this.id}`);
console.log(gameObject.playerSelections);
checkForWin();
// for (let i = 0; i < gameObject.colorSequence.length; i++) {
// playerSelections[i] = (`$${this.id}`);
// console.log(playerSelections)
// }
})
})
function checkForWin(){
if (gameObject.playerSelections === gameObject.colorSequence){
console.log('Comparing')
if (gameObject.playerSelections === gameObject.colorSequence){
console.log('You got it. Way to go!');
gameObject.colorSequence = [];
gameObject.playerSelections = [];
gameObject.currentLevel += 1;
$('.colors').off('click');
return 'You got it. Way to go!';
} else {
gameObject.colorSequence = [];
gameObject.playerSelections = [];
$('.colors').off('click')
console.log('Better luck next time!');
}
}
}
Since playerSelections and colorSequence are arrays, your the condition gameObject.playerSelections === gameObject.colorSequence tests that the array references are equal, not the contents of the arrays.
You need to check that each element of the array is equal:
How to check identical array in most efficient way?

Find all the low numbers in an array

I have an application that takes in the values of ten questions through a select drop down box. The values are 1 - 5 for each drop down menu. When the user clicks on the submit button, I store all the values from the input boxes in an object and then send them to a $.post request route. Within this post request route on server side, I get the post data sent to server, and loop through an array of 'friends', subtracting each scores array to the scores the user selected. I need to record which friend has the lowest difference and send it back, but I cant figure out how to send back multiple 'friends' that may have the same lowest number.
frontside.js
$('#submit').on('click', function(){
var newProfile = {
name: $('#name').val().trim(),
photo: $('#link').val().trim(),
scores: []
};
for(var x = 0; x < questions.length; x++){
var num = parseInt($('select[name = "q' + (x+1) + '"]').val());
newProfile.scores.push(num);
}
alert("Adding profile");
var currentURL = window.location.origin;
$.post(currentURL + "/api/friends", newProfile).done(function(data){
console.log('data', data);
});
server.js
var friends = require('./../data/friends.js');
app.post('/api/friends', function(req, res){
console.log('hi')
var person = req.body;
var diff = [];
var low = 0;
var match = [];
for(var x = 0; x < friends.candidates.length; x++){
for(var i = 0; i < friends.candidates[x].scores.length; i++){
var result = person.scores[i] - friends.candidates[x].scores[i];
if(result < 0){
var positive = result * (-1);
diff.push(positive);
}
else
diff.push(result);
}
//adding up the differences from each score
var added = diff.reduce(function(a, b){
return a + b;
}, 0);
//This is where I need to figure out how to store multiple lowest numbers of same value.
if(x === 0){
low = added;
match.push(friends.candidates[x]);
}
else if(low > added){
low = added;
match[0] = friends.candidates[x];
}
finalNum.push(added);
diff = [];
}
friends.candidates.push(person);
res.send(match);
});
friends.js
exports.candidates = [
{
scores:[5,1,4,4,5,1,2,5,4,1]
},
{
scores:[4,2,5,1,3,2,2,1,3,2]
},
{
scores:[5,2,2,2,4,1,3,2,5,5]
},
{
scores:[3,3,4,2,2,1,3,2,2,3]
},
{
scores:[4,3,4,1,5,2,5,3,1,4]
},
{
scores:[4,4,2,3,2,2,3,2,4,5]
},
{
scores:[2,3,3,3,3,3,3,3,3,3]
},
{
scores:[5,2,1,1,5,2,1,1,4,4]
}];
Try this.
// holds the minimum difference
var minDiff = Number.MAX_SAFE_INTEGER;
// holds the list of friends with minimum difference
var minDiffFriends = [];
for(var x = 0; x < friends.candidates.length; x++){
// variable to hold sum of differences
var scoreSum = 0
for(var i = 0; i < friends.candidates[x].scores.length; i++){
var result = person.scores[i] - friends.candidates[x].scores[i];
if(result < 0){
result = result * (-1);
}
scoreSum += result;
}
if(scoreSum < minDiff) {
minDiff = scoreSum ;
//clear previous array
minDiffFriends.length = 0;
//add the current friend information
minDiffFriends.push(friends.candidates[x]);
}
else if(scoreSum ==minDiff) {
// store friend information
minDiffFriends.push(friends.candidates[x]);
}
}

Working with local storage on AngularJS for shopping cart

I'm just starting out to build a simple shopping cart using AngularJS. I've now completed all the CRUD operations for the cart and now want to persist the cart for 3 days using local storage. I also want to be able to check local storage and retrieve cart when user visits the site again. Below is my code. Any help will be appreciated;
JS code
$scope.items = <?php echo json_encode($item_array); ?>;
$scope.cart = [];
$scope.deleteItem = function(item) {
var cart = $scope.cart;
var match = getMatchedCartItem(item);
if (match.count) {
cart.splice(cart.indexOf(item), 1);
return;
}
}
$scope.addItem = function(item) {
var match = getMatchedCartItem(item);
if (match) {
match.count += 1;
return;
}
var itemToAdd = angular.copy(item);
itemToAdd.count = 1;
$scope.cart.push(itemToAdd);
}
$scope.incQty = function(item) {
var match = getMatchedCartItem(item);
if (match) {
match.count += 1;
return;
}
}
$scope.decQty = function(item) {
var cart = $scope.cart;
var match = getMatchedCartItem(item);
if (match.count > 1) {
match.count -= 1;
return;
}
cart.splice(cart.indexOf(item), 1);
}
$scope.subTotal = function() {
var subtotal = 0;
for (var i = 0, max = $scope.cart.length; i < max; i++) {
subtotal += $scope.cart[i].price * $scope.cart[i].count;
}
$scope.subtotal = subtotal;
}
$scope.calcTotal = function() {
var total = 0;
for (var i = 0, max = $scope.cart.length; i < max; i++) {
total += $scope.cart[i].price * $scope.cart[i].count;
}
$scope.total = total + $scope.qwickCharge;
}
In my HTML i'm using ng-repeat to list out items and ng-repeat to list out cart array items. The CRUD is done using ng-click to call the functions.
That all works perfect. I now just need to be able to make $scope.cartpersistent in localStorage. Check if localStorage has a cart data and load them for users.
On startup, you can ask if localStorage is available:
if(typeof(Storage) !== "undefined") {
If it is available, you can check if you already saved data for the user:
if(localStorage.getItem("cart")) {
if(checkDate(localStorage.getItem("lastSave"))) {
$scope.cart = localStorage.getItem("cart");
} else {
$scope.cart = {};
}
}
The function checkDate() should check, if the data is still fresh or if 3 days are over and you need to load new data
If the user is done and presses save or something like that, you just override his old data and save the current date:
localStorage.setItem("cart", $scope.cart);
localStorage.setItem("lastSave", new Date().getTime() + (3 * 24 * 60 * 60 * 1000));
CheckDate() could look like this:
function checkDate(date) {
if(date < new Date().getTime()) {
return false;
}
return true;
}
Notice the change when i save the date, i now calculate the day 3 days away from today. Then in checkDate() you just check if the saved date (which is 3 days ahead) is less the date we have today. if it is less, 3 days are over and you have to get a new cart. Hope this helps :)

Categories

Resources