0

functional programing like the big wave that effect our coding habit,like forEach.

Despite For in javascript is pretty convenient and util. I want the whole loop look like functional so I set the array to stead for let index = 0...:

pure javscript

for(let index = 0;index < 10;index++){
   //count 10 times.
}

functional Solution

Array(10).forEach((value,index,arr)=>{
  //count 10 times. 
})

When array is made that empty items in self, So I use fill to solve this problem, the fill made functional complex.

Is any way to make item in Array or instead for cleary?

Derek 朕會功夫
  • 84,678
  • 41
  • 166
  • 228
Rach Chen
  • 1,132
  • 1
  • 8
  • 26
  • supported the solution code : `Array(10).fill().forEach(()=>{})` – Rach Chen Nov 29 '17 at 05:58
  • What are you trying to achieve ? – Hassan Imam Nov 29 '17 at 06:00
  • want to use `foreach` to achieve the `for` ,like I set `10` and it would run 10 times. – Rach Chen Nov 29 '17 at 06:02
  • 4
    It is a serious kludge to create an array so you can use *forEach* instead of a plain *for* loop. It will also likely run more slowly. Consider `for(let i=10; --i;){}` which is less to type and more performant. – RobG Nov 29 '17 at 06:03
  • @RobG hi rob, Is new the array and took memory that effect the performace? – Rach Chen Nov 29 '17 at 06:05
  • It's likely not an issue as a one off, but if you're doing it in many places, and with large loops, certainly. – RobG Nov 29 '17 at 06:06
  • 1
    @RachChen all the functions like `forEach`, `,map` are meant to make data manipulation more readable. They are never meant to replace `for` or `while`. The objective of these functions is, make reading easy. So If I read, `array.filter(...)` I will just look at condition and understand its purpose. Same thing, if implemented using for will be less readable as I will have to read entire thing. – Rajesh Nov 29 '17 at 06:08
  • 1
    Also, you can't (sensibly) break out of *forEach*, it must run for the entire length, it can't replace *do* or *while* loops. – RobG Nov 29 '17 at 06:09
  • If you want to toy around, you could e.g. write `repeat = (cb, n) => { while (n-- > 0) cb(n) }; repeat((n) => console.log(n), 5);` - for real productive code I'd go with fast, simple for-loops. – le_m Nov 29 '17 at 06:30
  • `forEach` is for side-effects; it's not functional – Thank you Nov 29 '17 at 15:30
  • Is duplicate ? I even didn't see any pure `functional` solution. – Rach Chen Nov 30 '17 at 01:43

1 Answers1

0

If you want to write in a truly functional manner, you might want to implement it yourself:

function range(n){
    if(n <= 0)  return [];
    else        return range(n-1).concat([n]);
}

range(10).forEach(n => /* do stuff */);

Keep in mind that, if your code is truly functional, there shouldn't be a need for a forEach loop because it will only cause side effects, and you don't want that in functional programming.

Derek 朕會功夫
  • 84,678
  • 41
  • 166
  • 228