Thank you for your question Eckehard, at first sight here is what I would do:
consttest=(x,i)=>console.log(x+i)function_loop(n,fn,args){[...Array(n)].forEach((_,i)=>fn([...args].join(''),i+1))}_loop(6,test,"This is a test ");console.log("_____________________________")constloop=curry(_loop);loop(5,test,"this is a test ");loop(5,test)("this is a test ");loop(5)(test)("this is a test ");loop(5)(test,"this is a test ");
Here is a possible answer. If I find something clearer i will post it
consttest=(x,i)=>console.log(x+i)function_loop(n,fn,args){[...Array(n)].forEach((_,i)=>fn([...args].join(''),i+1))}_loop(6,test,"This is a test ");console.log("_____________________________")constloop=curry(_loop);loop(5,test,"this is a test ");loop(5,test)("this is a test ");loop(5)(test)("this is a test ");loop(5)(test,"this is a test ");
I´m not sure this works: fn([...args].join('')? And you can call it loop(), as there is no loop keyword in JS. Anyway, a nice option.
Here are 3 working versions
functionloop1(n,fn,...args){for (leti=0;i<n;i++)fn(...args,i+1)}functionloop2(n,fn,...args){if (n>1)loop2(n-1,fn,...args)fn(...args,n)}function_loop(n,fn,...args){[...Array(n)].forEach((_,i)=>fn(...args,i+1))}functiontest(x,y,i){console.log(x,y*i)}loop1(3,test,"This is loop 1:",10);console.log("-----------")loop2(3,test,"This is loop 2:",10);console.log("-----------")_loop(3,test,"This is loop 3:",10);console.log("-----------")
Thank you for your question Eckehard, at first sight here is what I would do:
Demo
FInally you could write :
Demo
Thanks, to gave me the idea to include such a loop, in my micro lib :-)
Do you know a way to build a simplified but readable loop? Instead of for( let i=0; i<5; i++) fn(args)
Ideally it would be
loop(5) { ... }
We can do things like this, but this is far from ideal:
Demo
Hy Eckehard
Here is a possible answer.
If I find something clearer i will post it
Demo
Hy,
I´m not sure this works:
fn([...args].join('')
? And you can call itloop()
, as there is no loop keyword in JS. Anyway, a nice option.Here are 3 working versions
Demo
Eckehard, have you clicked on the démo link?
That works perfectly
Those functions can t be curried
I really liké the recursion way
The Demo works, but only with a single string parameter. Neither multiple arguments nor a numerical parameter seem to work.
And this version ? :
Thank you for the suggestions.
Demo
In my understanding, loop should be a shortcut for "for". So it should not be too specific. The most common use would be:
I agree with this seems the most elegant way.
And if one wish all sort of variations is possible :
Demo
Cool, just don´t forget to call
fn(...args, n)
, otherwise you cannot access the index from within your function.And you should decide, if the index counts from from 1 to n (which is intuitive) or from 0 to n-1, which makes it easier to deal with array indices.
Happy coding!
:-) Thank you Eckehard
Hy Eckehard,
I published a answer
Regards