CodePlexProject Hosting for Open Source Software

The

That is the technical explanation--but what does the

Say that you have an array of integers that you want to add together:

```
var arr = [1, 2, 3, 4, 5];
```

function sumArray(arr) { var total = 0; for (var i = 0; i < arr.length; i++) { total += arr[i]; } return total; }

Loop Variable, i |
Value of arr[i] |
Value of 'total' |
---|---|---|

0 | 1 | 1 |

1 | 2 | 3 (i.e., 1 + 2} |

2 | 3 | 6 (i.e., 1 + 2 + 3) |

3 | 4 | 10 (i.e., 1 + 2 + 3 + 4) |

4 | 5 | 15 (i.e., 1 + 2 + 3 + 4 + 5) |

If you used the

// results = [1, 3, 6, 10, 15] var results = $linq(arr).scan("(x, y) => x + y").toArray();

So, what does the

Let's take the table from the example for the

Loop Variable, i |
Value of arr[i] |
Value of 'total' |
Value of 'total' before adding arr[i] |
---|---|---|---|

0 | 1 | 1 | 0 |

1 | 2 | 3 (i.e., 1 + 2} | 1 |

2 | 3 | 6 (i.e., 1 + 2 + 3) | 3 (i.e., 1 + 2) |

3 | 4 | 10 (i.e., 1 + 2 + 3 + 4) | 6 (i.e., 1 + 2 + 3) |

4 | 5 | 15 (i.e., 1 + 2 + 3 + 4 + 5) | 10 (i.e., 1 + 2 + 3 + 4) |

If you used the

// results = [0, 1, 3, 6, 10] // Note: the second parameter of '0' is the initial value of the 'total' variable in the // loop of the sumArray function. var results = $linq(arr).prescan("(x, y) => x + y", 0).toArray();

Incidentally, if you "zip" (using addition) the initial array with the

var arr = [1, 2, 3, 4, 5]; // results1 = [0, 1, 3, 6, 10] var results1 = $linq(arr).prescan("(x, y) => x + y", 0).toArray(); // results2 = [1, 3, 6, 10, 15] var results2 = $linq(arr).zip(results1, "(x, y) => x + y").toArray(); // results3 = [1, 3, 6, 10, 15] var results3 = $linq(arr).scan("(x, y) => x + y").toArray(); // results2 == results3

Last edited Dec 5, 2012 at 5:00 AM by battousai999, version 2