Creating a Counter - Javascript - javascript

My apologies in advance if this is a very basic question/answer - I have searched, and am "old" learning for the first time and have found myself a little lost.
It's my first time coding, and basically I have an array (lets say fruits), I've been able to create it displaying the array and shuffling that array on click - which is exactly what I wanted (yay go me).
Now I am trying to have the ability to keep track of how many times I have clicked the shuffle button = before I either click reset, leave the page or refresh the page in which the counter resets.
This is where my trouble lays. I am having trouble 'inter-twining' the array + how many times I have clicked shuffle into my code. Honestly, I am getting confused, with so many 'help blogs' who all have different ways of doing things and I'd truly TRULY appreciate any help to get me sorted.
This is my current code to produce the list of fruits and being able to display it on my page.
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const r = Math.floor(Math.random() * (i + 1));
[arr[i], arr[r]] = [arr[r], arr[i]];
}
return arr;
};
const array = ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"];
function printArray(arr) {
return arr.reduce((acc, n, i) => {
return acc.concat(i < arr.length - 1 ? `${n}\n ` : `${n}`);
}, '');
};
function shuffle() {
const copiedArr = array.map(n => n);
const shuffledArray = shuffleArray(copiedArr);
document.getElementById("array").innerText = printArray(shuffledArray);
}
function restore() {
document.getElementById("array").innerText = printArray(array);
}
restore();
<div class="container">
<span id="array"><pre></pre></span>
</div>
<br>
<br>
<button onclick="shuffle()" value="randomize">Shuffle!</button>
<button onclick="restore()">Retore</button>
To be honest I have tried so many different things I am lost and confused. And so am hoping to start from scratch this is my code and I am trying to get a counter to keep track of every time I click shuffle that resets when Reset is clicked.

Here you go. While swahili geeks answer is correct. It is quite confusing for a learner.
So I took a different approach. You define a state object for your application and work upon it.
It would be nice to wrap the whole thing in a function to isolate the scope of declared functions and variables and not pollute the window, but you get there on your speed.
Also note how I am using a spread operator [...arr] to clone an array. No need to .map(n => n)
const state = {
originalArray: ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"],
currentArray: ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"],
numberOfShuffles: 0,
};
const outputElement = document.getElementById("js-array");
const counterElement = document.getElementById("js-count");
function formatArray(arr) {
return arr.reduce((acc, n, i) => {
return acc.concat(i < arr.length - 1 ? `${n}\n` : `${n}`);
}, "");
}
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const r = Math.floor(Math.random() * (i + 1));
[arr[i], arr[r]] = [arr[r], arr[i]];
}
return arr;
}
function shuffle() {
const copiedArr = [...state.currentArray];
const shuffledArr = shuffleArray(copiedArr);
state.currentArray = shuffledArr;
state.numberOfShuffles++;
updateUi();
}
function restore() {
state.currentArray = [...state.originalArray];
state.numberOfShuffles = 0;
updateUi();
}
function updateUi() {
outputElement.innerText = formatArray(state.currentArray);
counterElement.innerText = state.numberOfShuffles;
}
updateUi();
<pre id="js-array"></pre>
<br />
<span id="js-count"></span>
<br />
<br />
<button onclick="shuffle()">Shuffle!</button>
<button onclick="restore()">Restore</button>

The closure in JavaScript can be solution but it's a bit challenging to understand.
const add = (function () {
let counter = 0;
return function () {counter += 1;
return counter}
})();
// Call add() 3 times
add();
add();
add();
// the counter is now 3
The variable add is assigned to the return value of a self-invoking function.
The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.
This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.
This is called a JavaScript closure. It makes it possible for a function to have "private" variables.
The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

Related

For Loop items aren't adding into basket

My sumUpItems function works well. However, I am having problems with adding up items into basket. The second function isn't working. What I am doing wrong?
sumUpItems() {
let sum = 0;
for (const item of this.basketItems) {
sum += Number.parseFloat(item.price);
}
return sum;
},
basketCount() {
let count = 0;
for (let item of this.basketItems) {
count = ++item;
}
return count;
}
}
sumUpItems()
You can simplify the sumUpItems by using the reduce function which you can call on an array this.basketItems.
The most short way is:
sumUpItems() {
return this.basketItems.reduce((totalPrice, basketItem) => totalPrice + basketItem.price, 0);
}
What the reduce function does is it executes a reducer function on each element of the array, resulting in single output value, in this case the totalPrice of all basketItems.
if you are more comfortable with brackets you could write it down like this:
sumUpItems() {
return this.basketItems.reduce((totalPrice, basketItem) => {
return totalPrice + basketItem.price;
}, 0);
}
Or in ES5 javascript (without arrow function):
sumUpItems() {
return this.basketItems.reduce(function(totalPrice, basketItem) {
return totalPrice + basketItem.price;
}, 0);
}
I recommend you to rename the sumUpItems() function name to getTotalPrice() or something like that, it describes more specifically what the function does and returns.
BasketCount()
The reason why basketCount() is not returning the correct amount of items is because the incrementation of the variable count is invalid. let item holds the object value of the array item inside this.basketItems and you are trying to add this object to a number.
What you can do is return the length of the this.basketItems directly by writing:
basketCount() {
return this.basketItems.length;
}
Extra information
Reduce function documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
There are some powerfull methods that you can call on an array.
Most commonly the map, filter and reduce method. The reduce method is a bit tricky when you start using them but they can be handy in cases like this.
I recommend you to read this article on medium: https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d or search on google for map,filter and reduce javascript arrays, it will help you a lot ;)
Check the code very well, in basketCount() function the count variable is not incrementing and besides you increment item by 1 before assigning its value into count;
Are you planning doing something like this;
count += ++item;
or
count += item;
It will be better if you can include code for basketItems also;
If you rewrote this section like so: it will work
basketCount() {
let count = 0;
for (let item of this.basketItems) {
++count;
}
return count;
}
But a better way of doing this will do like so:
let d = 0;
let p = arr.map(eachone => d++); //p contains your count
Another option using forEach:
let arr = [1,2,3,4,5]; //replace arr with this.baskets
let b = 0;
arr.forEach((eachone) => {
b++
});
LASTLY: if you dont want to create an unused variable:
let baskets = [1,2,3,4,5];
let p = 0;
for(i=0; i<=baskets.length; i++) {
p++;
}
return p;
Welcome to stackover flow :)

Random Quote Machine - The new quote should not equal the last

I'm working on the FreeCodeCamp 'Random Quote Machine' front end library project using React JSX, which was working fine with the exception that it frequently produced the same quote two or three times in a row. This was not a good thing for a user to exprience.
Looking into Math.random() I quickly realisded that this was quite normal - two or three repeats of the same number in a row. This is the code I had in a React method called getQuote:
// get new quote from array
getQuote() {
let x = Math.floor(Math.random() * quotes.length);
{console.log("random num = ", x)};
this.setState(quotes[x]
);
This meant that I had to write a method of producing a random number that wasn't the same as the last. Which, thanks to the quality content on this site and input from #Etienne Martin I found pretty quickly:
Most of the answers in this thread are over complicated.
Here's a concise example of how I would do that:
function getNumber(){
return (getNumber.number = Math.floor(Math.random() * (4 + 1))) === getNumber.lastNumber ? getNumber() : getNumber.lastNumber = getNumber.number; }
console.log(getNumber()); // Generates a random number between 0 and 4
Live example: https://jsfiddle.net/menv0tur/3/ share edit flag edited
Apr 22 '17 at 16:25 answered Apr 20 '17 at 19:35
This allowed me to write my own method:
getQuote() {
const randNum = () => {
return (randNum.x = Math.floor(Math.random() * (quotes.length))) === randNum.y ? randNum() : randNum.y = randNum.x;
}
this.setState(quotes[randNum()])
}
My problem is; I don't fully understand it. Specifically getNumber.number it looks as though it is using dot notation to access a key value of our function getNumber(). I have never seen this before. As you can see in my re-write I defined the function name randNum() and I'm using randNum.x and randNum.y instead of getNumber.number and getNumber.lastNumber.
Could someone kindly enlighten me as to exactly what we are doing here?
Many thanks in advance.
The first thing you should know is that a function is an object at the same time in javascript. So I can do this:
const randNum = () => {}
randNum.property = "value";
and that's exactly what your function is doing. Probably it will be better to write it as:
const randNum = () => {
randNum.x = Math.floor(Math.random() * (quotes.length));
// I can access randNum.x and randNum.y because randNum is a function and an object
if (randNum.x === randNum.y) {
// current value is the same as older value, run the function again
return randNum();
} else {
// current value is not the same as the older value
randNum.y = randNum.x;
return randNum.y;
}
};
or, even better:
let oldValue;
const randNum = () => {
const currentValue = Math.floor(Math.random() * (quotes.length));
if (currentValue === oldValue) {
return randNum();
} else {
oldValue = currentValue;
return currentValue;
}
};
I know this is not a one line solution but is easier to understand what it does (in my opinion)
Let's rewrite getNumber function so that it's more readable:
function getNumber() {
let result;
if (
(getNumber.number = Math.floor(Math.random() * (4 + 1))) ===
getNumber.lastNumber
) {
result = getNumber(); // recursive call
} else {
result = getNumber.lastNumber = getNumber.number; // assignment expression
}
return result;
}
As you can see the function uses recursion. Also in this line: result = getNumber.lastNumber = getNumber.number; the code getNumber.lastNumber = getNumber.number is an assignment expression so result is the same as getNumber.number. Lastly it's possible to write getNumber.number because getNumber is an object. In Javascript even functions are objects. So when you call getNumber() you invoke the function, when you call getNumber.number you accessing object field.
After you define the function getNumber you can then add as many fields to it as you want for example getNumber.anotherProperty = 'whatever' then console.log(getNumber.anotherProperty) // logs 'whatever'.
You may populate your state with a shuffled version of array of quotes, popping one at a time upon nextQuote until all of them are shown, then repeat, once your shuffled array is empty, thus, the quote will not appear until all the rest are shown.
However, it does not eliminate probability of the following outcome:
quote1, quote3, quote5, quote4 | quote5, quote1, quote3..
Pushing the distance between quotes further ultimately leads you to the point where the interval of repeating for each quote is source array length, i.e. your initial array going round:
quote1, quote2... , quote5| quote1, quote2..., quote5 | quote1, quote2...
But then it won't be random quotes any longer
Live-demo of my approach, you may find as follows:
const { useState } = React,
{ render } = ReactDOM,
rootNode = document.getElementById('root')
const quotes = ['quote1', 'quote2', 'quote3', 'quote4', 'quote5'],
shuffle = arr => [...arr].reduceRight((r,_,__,s) =>
(r.push(s.splice(0|Math.random()*s.length,1)[0]), r),[])
const App = () => {
const [currentQuote, setCurrentQuote] = useState(quotes[0|Math.random()*quotes.length]),
[quoteList, setQuoteList] = useState(shuffle(quotes).filter(q => q!= currentQuote)),
nextQuote = () => {
const [newQuote, ...rest] = quoteList
!rest.length ?
setQuoteList(shuffle(quotes).filter(q => q != newQuote)) :
setQuoteList(rest)
setCurrentQuote(newQuote)
}
return (
<div>
<div>{currentQuote}</div>
<button onClick={() => nextQuote()}>Next</button>
</div>
)
}
render (
<App />,
rootNode
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

setTimeout and recursive IFFEs, nested!? How to calculate the delay.

This problem has really reminded me where I am regarding JS skills... :(
I feel I'm right on the cusp but I'm struggling to understand what to do conceptually, it's not so much a syntax issue as I feel I almost cracked it.
What I need
I'm trying to console.log a series of strings, one letter at a time.
There needs to be a delay between each LETTER outputted, say 300ms.
There must then be a delay between each STRING outputted, say 2000ms.
There are 2 strings in example array, but solution must support a dynamic number of strings.
My Current Code (can be pasted into a console)
var stringList = ['first test','second test'],
stringListLen = stringList.length;
for(var i = 0; i < stringListLen; i++){
// begin with first string and read it's length for iterations
var stringNumber = 0;
var currentString = stringList[stringNumber];
var currentStringLen = currentString.length;
// just see the word for clarification at this point in code
console.log(currentString);
(function (i) {
setTimeout(function () {
for (var j = 0; j < currentStringLen; j++) {
(function (j) {
setTimeout(function () {
// THE MAGIC HAPPENS HERE
console.log(j, currentString.charAt(j));
// End of string, so read next string, reset letter count
if(j === currentStringLen - 1){
stringNumber++;
currentString = stringList[stringNumber];
j = 0;
}
}, 300 * j); // each letter * specified delay
})(j);
};
}, currentStringLen * 300 * i); // letter * delay * letters in word
})(i);
}
The Issue
THE GOOD: I am successfully getting the short delay between letters outputted, and my check to switch to a new word and reset the letter counter when we get to the end of the first word is working...
THE BAD: I can't get the wait between the two words to work. I have tried a few ideas and have just got myself so confused I don't know if my approach is correct now.
THE UGLY: The final letter of the last term is also not outputting, and that is just totally unexpected.
What I've tried.
Okay, I've tried simply changing the "currentStringLen * 300 * i" elements to various combinations that seemed logical but had no effect better or worse. Ultimately I think I am trying to calculate "wait the number of letters in current string times 300 (the letter delay) * " <---- STRIKETHROUGH...
I actually don't know what I'm calculating and that's the issue.
I now think I want to split this into TWO functions, not two nested ones. One to READ AND PASS IN a string to another function that JUST outputs the letters with a short delay, then once it gets to the last letter it calls the first function asking for the next word. BUT then I'm still going to need to recurse for the number of strings in the array which creates the same issue...
Am I missing anything fundamental here people?
Is this roughly what you had in mind?
function printLetters(stringList) {
var wordIndex = 0,
letterIndex = 0;
printNext();
function printNext() {
var word = stringList[wordIndex];
var letter = word.charAt(letterIndex);
console.log(letter);
++letterIndex;
if (letterIndex === word.length) {
letterIndex = 0;
++wordIndex;
if (wordIndex < stringList.length) {
setTimeout(printNext, 2000);
}
return;
}
setTimeout(printNext, 300);
}
}
printLetters(['first test', 'second test']);
Here there's only ever one setTimeout running at once and a new one is being set as required with the appropriate time.
While I don't recommend having multiple timers running at once, it can be done. Something like this:
function printLetters(stringList) {
var letterCount = 0,
startTime = Date.now();
stringList.forEach(function(word, wordCount) {
word.split('').forEach(function(letter) {
setTimeout(function() {
console.log(letter, Date.now() - startTime);
}, wordCount * 1700 + (letterCount * 300));
++letterCount;
});
});
}
printLetters(['first test', 'second test']);
Here I've included the time delta in the logging to give a better sense of what is going on when. The gap between strings is 2000 but the constant in the code is 1700 because there's already 300 being added.
I would do a quite different approach. Rather than doing a bunch of precalculated timeouts and their associated closures, i would do just one timeout at a time, using recursion to then move on to the next timeout:
function delayShow(words) {
if (!words || words.length === 0) {
return;
} else if (words[0].length === 0) {
words.shift()
setTimeout(() => delayShow(words), 2000);
} else {
console.log(words[0].charAt(0));
words[0] = words[0].substr(1);
setTimeout(() => delayShow(words), 300);
}
}
delayShow(['first test','second test']);
You can use a condition inside the loop, and when you're on the last iteration of the strings characters, you call the recursive function again, inside a timeout, to iterate over the next string in the array etc.
var stringList = ['first test', 'second test'];
(function rec(j) {
var chars = stringList[j].split('');
chars.forEach(function(char, i) {
setTimeout(function() {
console.log(char);
// if it's the last iteration && there are more strings in the array
if ((i == (chars.length - 1)) && (j < stringList.length - 1)) {
setTimeout( function() {
rec(++j); // play it again
}, 2000);
}
}, i * 300);
});
})(0);
Even something as trivial as setTimeout's, is a good example of using async / await. So I've included an example below.
As you will see, the code is much easier to follow. With the added advantage of not creating multiple setTimeout's running concurrently,.
It also really helps make things much easier to change things, eg. If I asked you to alter the code below so that SPACE takes less time than other letters, to make it flow more naturally, it wouldn't take a lot of thought to work out what to change.
var
stringList = ['first test','second test'];
async function delay(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
async function run() {
let wordpos = 0;
let wordElem = document.querySelector('.words');
while (true) {
let word = stringList[wordpos];
let text = '';
for (var letterpos = 0; letterpos < word.length; letterpos ++ ) {
let letter = word[letterpos];
text = text + letter;
wordElem.innerText = text;
await delay(300);
}
await delay(2000);
wordpos = (wordpos + 1) % stringList.length;
}
}
run();
<h1 class="words">?</h1>

Javascript reverse array of numbers and subtract 2, then 1, then 0 then add 1, add 2 etc

Sorry for the awful title. I've crashed enough browsers and asking for help.
Here's the specific problem I'm trying to solve.
Create a function called 'reversedLooper' that when passed an array will loop through it backwards and subtract 2 from the last element, 1 from the second to last, 0 from to the third to last, add one to the fourth to last, add 2 to the fifth to last, etc. until it reaches the front of the array. Return the list when you are done
It's easy with [].map:
myArray.map(function(item, index, arr) {
return item + arr.length - index - 3;
});
Here is a shorter, more concise version.
function reversedLooper(arr){
var increaseBy = -2;
for(var i = arr.length - 1; i >= 0; i--){
arr[i] += increaseBy;
increaseBy++
}
return arr;
}
It's real ugly, but appears to satisfy the test cases.
var array = [1,2,3,4,5,6,7,8,9,10,11,12,13];
function reversedLooper(array) {
var newArray = [];
var n = -3;
for (var i = array.length - 1; i >= 0; i--) {
n++;
if (array[i] === array.length) {
newArray.push(array[i] - 2);
}
else if (array[i] === array.length - 1) {
newArray.push(array[i] - 1);
}
else if (array[i] === array.length - 2) {
newArray.push(array[i]);
}
else {
newArray.push(array[i] + n)
}
}
return newArray;
}
console.log(reversedLooper(array));
Building on my comment, I will use the new fiddle plug in to make something to show you here.
let list = Immutable.List.of(1,2,3,4,5)
function createListOperationsMapping(list) {
// Maybe consider dynamically creating a mapping of methods to indexes
// If you return a Map from this that is something like:
/*
Map({
0: (item) => item - 2,
1: (item) => item - 1,
// since there's a case where you subtract 0, so no change
2: (item) => item,
3: (item) => item + 1,
4: (item) => item + 2,
5: (item) => item + 3,
// etc...
})
*/
// This would allow you to map the reversedList and based on the index you could just
// call the method from the map...
// Like this (where the map from above ^^ is called listOperationMap)
/*
var mutatedReversedList = reversedList.map((item, index) => {
return listOperationMap[index](item);
})
Notice I used the word "mutated" here. If you use Immutable,
you're actually returning a copy with updates rather than mutating,
but I wanted to make it clear that the result of mapping the
Immutable List will be a new Immutable List - not the mutated
previous list. Also, if you choose to work with Immutable, remember
you will need to set new variables for return values of updates to
the Immutable data structures.
*/
}
let reversedList = list.reverse()
let reversedListSize = reversedList.size
let newList = reversedList.map((listItem, index) => {
// Do stuff in here
})
console.log(list.toJS())
console.log(reversedList.toJS())
console.log(reversedListSize)
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.6/immutable.min.js"></script>
Since your question was a bit vague, I'm basically just throwing out some ideas based on what there was to work with. Hopefully this is useful in at least starting to explore how you might approach the problem you are trying to solve.
Either way, I recommend taking a look at Immutable.js.
PS: If you click on "Run code snippet", then crack open your dev tools and the console.log(s) will show up in your console.

JavaScript: Improving the performance of a FOR Loop to stop the browser locking up?

I have an array of objects, I loop through this array one object at a time and I make a couple of checks to see if each object in that array meets certain criteria, if that object meets this criteria I then copy a property of this object in to an array (that property also contains another object).
for(var v = 0; features.length > v; v++){
var feature = features[v];
//If the feature is on the map then we want to add it
if(feature.onScreen()){
dataArray.push(feature.attributes);
}
}
Now for some reason if this array of objects is big (5000+) in size this operation becomes very expensive and the browser just locks up for a second or two (Some times more).
I cant go in to much more info of what the code does but I was wondering given this loop, what would be the best way to give the browser a break lets say every 500 iterations and so it doesn't lock up and then continue on etc.
Thanks
Not sure... but what about putting that code into a function, then breaking out and recalling the function (say every xMs)?
eg,
var LastPos = 0;
function DoLoop()
{
for(var v = LastPos; features.length > v; v++){
var feature = features[v];
//If the feature is on the map then we want to add it
if(feature.onScreen()){
dataArray.push(feature.attributes);
}
if(v > 500)
{
LastPos = v;
break;
}
}
setTimeout('DoLoop()', 10);
}
setTimeOut() can solve this.
var maxStatement = 1000, currentIndex=0, timeoutVar = ''
var sLimit = features.length
function multiStepLoop(){
for (var i=currentIndex; i<currentIndex+maxStatement; i++){
//---DO YOUR STUFFS HERE
}
var a = sLimit-i;
currentIndex += maxStatement;
if (maxStatement >= a){ maxStatement=a }
if (a<=0){
callBackFunction() //-- function to call when your peocess finish.
}else{
timeoutVar = setTimeout('multiStepLoop()',1)
}
}
multiStepLoop();
The drawback is that you need to cover all you want to do after this process complete into a function, then run it like a callBack_Function.
Note : Jus need to set the time for setTimeout to 1 millisecond & the browser won't display the waiting-cursor.
Change the structure of the loop to :
var index = 0;
function myfunc() {
while(features.length > index){
var feature = features[v];
//If the feature is on the map then we want to add it
if(feature.onScreen()){
dataArray.push(feature.attributes);
}
index++;
//You can do this
var waitingTime = 0;
If (index% 500=0) waitingTime=100; //or 10, 20...
//Or just with a short interval
var waitingTime = 10;
setTimeOut('myfunc', waitingTime);
}
}
Or with a parameter : [I prefer this one]
function myfunc(index) {
if(!index) {
index=0;
}
while(features.length > index){
var feature = features[v];
//If the feature is on the map then we want to add it
if(feature.onScreen()){
dataArray.push(feature.attributes);
}
//You can do this
var waitingTime = 0;
If (index% 500=0) waitingTime=100; //or 10, 20...
//Or just with a short interval
var waitingTime = 10;
setTimeOut('myfunc', waitingTime);
}
}
[EDIT]
Change setTimeOut calls...
And in your code, when you call the function, don't give the param, to initialize the index!
What if you did something with a little burst and a little recursion:
Fiddle Code
Main Function
What happens is a given index is passed with a burst amount of intervals (i.e. 500), upon ending the for loop at the given number of burst iterations, it recalls itself with the same burst number. The function ends when the end of the features array is completed.
var transferFeatures = function (index, burst) {
for (var z = 0; z <= burst; z++) {
if (index === features.length) {
return;
}
var feature = features[index];
if (feature.onScreen) {
dataArray.push(feature.attributes);
}
index++;
}
if (index !== features.length) {
transferFeatures(index, burst);
}
};
Testing
To simulate load, I created an array of objects using various key-value pairs (most importantly, your attributes inner object):
//To simulate a random boolean
var randomBoolean = function () {
return Math.random() <= 0.5;
};
//A random integer
var getRand = function () {
return (Math.floor(Math.random() * 10).toString());
};
// Create a bunch of dummy objects
var randomFeatures = function (arr, i) {
for (var p = 0; p < i; p++) {
arr.push({
onScreen: randomBoolean(),
attributes: {
width: getRand(),
height: getRand(),
someAtt: "I'm just an attribute",
coolKidsRideBikes: true,
foo: "bar",
bar: "baz"
}
});
}
};
Granted, it's not the same onScreen() test you will be using, but either way, it evaluates to a boolean value. I think if you apply this concept with your code, you could have amazing results.
Everything in the Fiddle I linked too at the top is called like this:
randomFeatures(features, 5000);
console.log(features.length);
transferFeatures(0,500);
console.log(dataArray.length);
Load Testing
I simulated 5000000 (5 million) random objects being pushed onto features with a burst of 1000 and the script completed in around 3.29 seconds.

Categories

Resources