Skip to content

Commit 8893cfc

Browse files
committed
Add array.each()
1 parent 28e1d6f commit 8893cfc

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

examples/tests/arrays.tab

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,27 @@ assert(not a.includes(100))
9696
assert(not a.includes('abc'))
9797
############################################################################
9898

99+
############################################################################
100+
# Array.each
101+
#
102+
# The each function applies a function to each member of the array. It's
103+
# one of the Tablescript ways of "looping".
104+
a = [1, 2, 3, 4, 5]
105+
state = {
106+
value: 0
107+
}
108+
f = fn(state) { fn(n) { state.value = n } }
109+
assert(a.each(f(state)) == 5)
110+
assert(state.value == 5)
111+
112+
# The each function can also take a 2nd parameter that is the 0-based index
113+
# of the array member passed as the 1st parameter
114+
b = [0, 0, 0, 0, 0]
115+
f = fn(state) { fn(n, i) { state[i] = n + 1 } }
116+
assert(a.each(f(b)) == 6)
117+
assert(b == [2, 3, 4, 5, 6])
118+
############################################################################
119+
99120
############################################################################
100121
# Array.map
101122
#

src/values/array.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,15 @@ const multiplyBy = entries => (context, other) => createArrayValue(
8282
).reduce((all,n) => ([...all, ...entries]), [])
8383
);
8484

85+
const each = entries => createNativeFunctionValue(['f'], async context => {
86+
const f = requiredParameter(context, 'f');
87+
let result = context.factory.createUndefined();
88+
for (let i = 0; i < entries.length; i++) {
89+
result = await f.callFunction(context, [entries[i], context.factory.createNumericValue(i)]);
90+
}
91+
return result;
92+
});
93+
8594
const reduce = entries => createNativeFunctionValue(['reducer', 'initialValue'], async context => {
8695
const reducer = requiredParameter(context, 'reducer');
8796
const initialValue = requiredParameter(context, 'initialValue');
@@ -218,6 +227,7 @@ export const createArrayValue = entries => createValue(
218227
identicalTo(entries),
219228
nativeEquals(entries),
220229
{
230+
each: each(entries),
221231
reduce: reduce(entries),
222232
map: map(entries),
223233
filter: filter(entries),

0 commit comments

Comments
 (0)