foreach_i
See original GitHub issueI’d like to propose a new util: foreach_i
.
Motivation
You know how JS’s Array.map
also passes the element index as a 2nd parameter to the function?
> ['a', 'b', 'c'].map((x, i) => `Element ${i} is ${x}`)
[ 'Element 0 is a', 'Element 1 is b', 'Element 2 is c' ]
That’s exactly what I’m trying to do here. The only difference is that the index would be passed as the 1st param:
def test_foreach_i():
r = ['a', 'b', 'c'] > (pipe
| foreach_i(lambda i, x: f'Element {i} is {x}')
| list
)
assert r == [ 'Element 0 is a'
, 'Element 1 is b'
, 'Element 2 is c'
]
(Naïve) Implementation
from pipetools.utils import foreach, as_args
from typing import Callable, TypeVar
A = TypeVar('A')
B = TypeVar('B')
def foreach_i(f: Callable[[int, A], B]):
return enumerate | foreach(as_args(f))
The same could be done for foreach_do
.
Issue Analytics
- State:
- Created a year ago
- Comments:6 (4 by maintainers)
Top Results From Across the Web
How do I use table.foreach() and table.foreachi()?
You pass an array and a callback function that gets called each iteration. table.foreach(tbl, function(val) ... end) table.foreachi(tbl, ...
Read more >API foreachi | WoWWiki - Fandom
Apply the function f to the elements of the table passed. On each iteration the function f is passed the index-value pair of...
Read more >Array.prototype.forEach() - JavaScript - MDN Web Docs
The forEach() method executes a provided function once for each array element.
Read more >Table Library Tutorial - lua-users wiki
foreachi () method is guaranteed to return indexed keys in order, and to skip non-index keys.) Apply the function f to the elements...
Read more >table.foreachi - Premake
table.foreachi ; Parameters. arr is an table containing indexed values. fn is the function to call for each non-nil element. The value (not...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I see. Technically, you can instead do:
But it’s quite unreadable.
I think what we could do is detect if a two-parameter function is being passed in and then pass two separate parameters - and otherwise pass in the tuple so things like
foreach_i("Element {0} is {1}")
still work as expected.Not really.
Every once in a while I find myself in a situation where I want to do a “foreach with index”. The particular piece of code that prompted me to write this issue was:
With
foreach_i
, it would become: