I would like to define a function which will act as a while
statement (with some addons, but for reasons of simplicity, I will show here a basic wrapper). So with conditions as the first parameter, and the callback to execute at each loop as the second one.
I came at first with this version:
const wrappedWhile = (conditions, callback) => {
let avoidInfinite = 0;
while (conditions) {
callback();
if (avoidInfinite >= 10) {
console.log('breaking while statement for avoiding infinite loop');
break;
}
avoidInfinite++;
}
};
let i = 0;
wrappedWhile(i < 5, () => {
console.log('log from callback: i =', i);
if (i >= 5) {
console.log('the loop continues whereas it should stop');
}
i++;
});
Logically, it is expected to stop when i >= 5
. But the conditions
parameter is a simple boolean in the wrappedWhile
function, so it is always true
as i
was less than 5
at call.
Then, I came up with another version where conditions
is evaluated at each iteration of the loop:
const wrappedWhile = (conditions, callback) => {
while (Function('return ' + conditions + ';')()) {
callback();
}
};
let i = 0;
wrappedWhile('i < 5', () => {
console.log('log from callback: i =', i);
i++;
});
But, if I am not wrong, Function
is using eval()
in order to work, and all of us once heard that the usage of eval()
is not really safe towards code injection.
Now my question is simple: are there more secure alternatives to do what I want to achieve?
After some researches, I found a link which shows a way to evalify in a sandbox environment, but I don't know if it is good way or not.
You should pass a function as a condition and call it in the while loop
const wrappedWhile = (conditions, callback) => {
let i = 0;
while (conditions(i)) {
callback(i);
if (i >= 10) {
console.log('breaking while statement for avoiding infinite loop');
break;
}
i++;
}
};
wrappedWhile((i) => (i < 5), (iteration) => {
console.log('log from callback: i =', iteration);
});