# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: 'Python 3.9.7 64-bit (''NLP-py39'': conda)'
#     language: python
#     name: python3
# ---

# ### Ubah source code dan penjelasan pada artikel untuk JavaScript ini, diubah menjadi Python
# (https://blog.bitsrc.io/understanding-higher-order-functions-in-javascript-75461803bad)

# ## Map

# #### Example 1#

# +
# Kode Javascript

# const arr1 = [1, 2, 3];
# const arr2 = arr1.map(function(item) {
#   return item * 2;
# });
# console.log(arr2);

# +
# kode di python

arr1 = [1, 2, 3]
arr2 = map(lambda a: a * 2, arr1)
print(list(arr2))
# -

# ### Example 2#

# +
# Kode Javascript

# const birthYear = [1975, 1997, 2002, 1995, 1985];
# const ages = birthYear.map(year => 2018 - year);
# // prints [ 43, 21, 16, 23, 33 ]
# console.log(ages);
# -

birthYear = [1975, 1997, 2002, 1995, 1985]
umur = map(lambda u: 2021 - u, birthYear)
print(list(umur))

# ## Filter

numbers = [13, 4, 18, 35]
div_by_5 = filter(lambda num: num % 5 == 0, numbers)
print(list(div_by_5))

# +
arbitrary_numbers = map(
    lambda num: num ** 3, filter(lambda num: num % 3 == 0, range(1, 21))
)

print(list(arbitrary_numbers))  # [27, 216, 729, 1728, 3375, 5832]

# +
# javascript

# const persons = [
#   { name: 'Peter', age: 16 },
#   { name: 'Mark', age: 18 },
#   { name: 'John', age: 27 },
#   { name: 'Jane', age: 14 },
#   { name: 'Tony', age: 24},
# ];
# const fullAge = persons.filter(person => person.age >= 18);
# console.log(fullAge);

# +
persons = [
    {"name": "Peter", "age": 16},
    {"name": "Mark", "age": 18},
    {"name": "John", "age": 27},
    {"name": "Jane", "age": 14},
    {"name": "Tony", "age": 24},
]

fullAge = filter(lambda umur: umur["age"] > 18, persons)
print(list(fullAge))
# -

# ### Reduce

# #### Example 1#

# +
# Javascript

# const arr = [5, 7, 1, 8, 4];
# const sum = arr.reduce(function(accumulator, currentValue) {
#   return accumulator + currentValue;
# });
# // prints 25
# console.log(sum);

# +
from functools import reduce

arr = [5, 7, 1, 8, 4]

sum = reduce(lambda accumulator, currentValue: accumulator + currentValue, arr)
print(sum)

StarcoderdataJupyterScriptsDedupFiltered