I need to keep a stack of 10 items (value primitives, not objects) where no item is repeated. Here's my initial stab at an implementation. Any suggestions for improvements?
var items = [];
function newItem() {
return Math.floor(Math.random() * 50);
}
function inArray(arr, val) {
var in_arr, i;
in_arr = false;
i = arr.length;
if (i < 1) {
return in_arr;
}
do {
if (arr[i - 1] === val) {
in_arr = true;
break;
}
} while (--i);
return in_arr;
}
function addItem() {
var new_item;
while (items.length > 9) {
items.shift();
}
do {
new_item = newItem();
} while (inArray(items, new_item));
items.push(new_item);
}
while (items.length > 9) {
items.shift();
}
can be written without iteration as
var len = items.length;
if (len > 9) {
items = items.slice(len - 9);
}
Since JS 1.6, inArray can be written as array.indexOf(element) != -1. Otherwise,
if (i < 1) {
return in_arr;
}
do {
if (arr[i - 1] === val) {
in_arr = true;
break;
}
} while (--i);
return in_arr;
can be written more simply as
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With