Well, I know my question is very difficult. But I want to know Things?
Suppose, I have an array element?
const array = [
"AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
]
I need here on Function that can run only 10 element every time. When I run function for first time it's show me first 10 element. Then If I run again then it show me the rest element.
Suppose this is function
const runElement = () => {
console.log(element)
}
If I run this function first time it show me first 10 element from array.
"AEDAUD"
"AEDCAD"
"AEDCHF"
"AEDEUR"
"AEDGBP"
"AEDINR"
"AEDJPY"
"AEDNOK"
"AEDNZD"
"AEDPKR"
Then If I run that function again it should show me the rest element-
"AEDSAR"
"AEDSEK"
"AEDZAR"
"ANG"
"ARSBRL"
"ARSEUR"
"ARSGBP"
If I run the function again it should go first 10 element again. In that It should run for always.
Is this possible in javascript?
Maybe you would be interested in using a generator: provide it with the array and the chunk size, and let it just cycle happily through the array for ever while yielding the results.
The iterator can be used to grab as many results as needed:
function* pullValues(arr, chunkSize) {
let i = 0;
while (true) {
yield arr.slice(i, i += chunkSize);
if (i >= arr.length) i = 0;
}
}
// demo
const array = [
"AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
];
let it = pullValues(array, 10);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
//....
You can use a variable to store a flag and the function can reference to this variable to output differently.
const array = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
];
let isShowFirstTenItem = true;
const show = () => {
let output;
if (isShowFirstTenItem) {
output = array.slice(0, 10);
} else {
output = array.slice(10, -1);
}
isShowFirstTenItem = !isShowFirstTenItem;
console.log(output);
};
show();
show();
show();
You can do something like this.
Here tracker is used to keep track of what elements are displayed already. If tracker is 0, nothing is displayed yet, if 1 it means, first ten is already displayed. For loop only displays 10 elements once.
const array = [
"AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
]
let tracker = 0;
const display = () => {
for(let i = tracker*10; i<10*tracker + 10 ; i++){
if(!array[i]) break;
console.log(array[i])
}
if(tracker >= array.length){
tracker = 0;
} else {
tracker = tracker+1
}
}
display()
display()