# Functional Programming Snippets in JavaScript and Julia

## Computing the Sum of a List of Elements

`> xs = [2, 4, 8][ 2, 4, 8 ]> xs.reduce((total, x) => total + x)14`
`julia> xs = [2, 4, 8]3-element Vector{Int64}: 2 4 8julia> sum(xs)14`
`julia> reduce((total, x) -> total + x, xs)14`
`julia> 3 + 47julia> +(3, 4)7`
`julia> reduce(+, xs)14`
`julia> factorial(4)24julia> reduce(*, 1:4)24`

## Gathering Values of a Dictionary

`> nums = [{number: "two"}, {number: "four"}]> nums.map(item => item.number).join(" ")'two four'`
`julia> nums = ["number" => "two", "number" => "four"]julia> join(map(last, nums), " ")"two four five"`
`julia> pair = "number" => "two""number" => "two"julia> first(pair)"number"julia> last(pair)"two"julia> range = 4:84:8julia> first(range)4julia> last(range)8`
`julia> map(range -> first(range), [2:8, 4:8, 5:6])3-element Vector{Int64}: 2 4 5`
`julia> map(first, [2:8, 4:8, 5:6])3-element Vector{Int64}: 2 4 5julia> map(last, [2:8, 4:8, 5:6])3-element Vector{Int64}: 8 8 6`

## Getting the Unicode Codepoints of Characters in String

`> [..."Þrúðvangr"].map(ch => ch.codePointAt())[  222, 114, 250, 240,  118,  97, 110, 103,  114]`
`julia> map(codepoint, ["Þrúðvangr"...])9-element Vector{UInt32}: 0x000000de 0x00000072 0x000000fa 0x000000f0 0x00000076 0x00000061 0x0000006e 0x00000067 0x00000072`
`map(codepoint, collect("Þrúðvangr"))broadcast(codepoint, collect("Þrúðvangr"))codepoint.(collect("Þrúðvangr"))`
`julia> broadcast(+, [3, 4], [2, 5])2-element Vector{Int64}: 5 9julia> broadcast(+, [3, 4], 10)2-element Vector{Int64}: 13 14`

## Creating a Dictionary From Array

`> chars = ['a', 'b', 'c'][ 'a', 'b', 'c' ]> chars.reduce((dict, ch, i) => {    dict[ch] = i;    return dict}, {});{ a: 0, b: 1, c: 2 }`
`> dict = {}{}> chars.forEach((ch, i) => dict[ch] = i)undefined> dict{ a: 0, b: 1, c: 2 }`
`julia> Dict(ch => i for (i, ch) in enumerate(chars))Dict{Char, Int64} with 3 entries:  'a' => 1  'c' => 3  'b' => 2`
`julia> [ch => i for (i, ch) in enumerate(chars)]3-element Vector{Pair{Char, Int64}}: 'a' => 1 'b' => 2 'c' => 3`

# Conclusion

`map(x -> x.foo, objects)`
`map(foo, objects)`

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

## More from Erik Engheim

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.