-
Notifications
You must be signed in to change notification settings - Fork 0
/
fp.gd
56 lines (39 loc) · 1.77 KB
/
fp.gd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Static service class for higher-order functions
# Will become obsolete in 4.0
# Adapted from: https://georgemarques.com.br/functional-gdscript.pdf
# Calls `function` on each element of `input`, returning the transformed outputs from `function`
# `function` is required to have a non-void output
static func map(input: Array, function: FuncRef) -> Array:
var result := []
result.resize(input.size())
for i in range(input.size()):
result[i] = function.call_func(input[i])
return result
# Calls `function` on each element of `input`, returning all the elements which returned `true`
# `function` should return a `bool`, but this is not required
static func filter(input: Array, function: FuncRef) -> Array:
var result := []
for element in input:
if function.call_func(element):
result.append(element)
return result
# Returns a single output value by calling `function` on each element of the array along with the accumalated result of each iteration
# `function` should take in two inputs
# `base` can optionally be used to define a starting value
static func reduce(input: Array, function: FuncRef, base = null):
var accumulator = base
var index := 0
if not base and input.size() > 0:
accumulator = input[0]
index = 1
while index < input.size():
accumulator = function.call_func(accumulator, input[index])
index += 1
return accumulator
# Transforms `input` in order through each `Funcref` pair in `pipe_pairs`.
# `pipe_pairs` is expected to be an array of arrays, with a higher-order function `Funcref` followed by an appropriate transformative function `Funcref`.
static func pipe(input: Array, pipe_pairs: Array):
var transformed_input = input
for pair in pipe_pairs:
transformed_input = pair[0].call_func(transformed_input, pair[1])
return transformed_input