The map function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.
In JavaScript, the map() function is used to transform each element of an array by applying a given function to it. It returns a new array with the transformed values. For example, if you have an array of numbers and want to square each element:
const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map((num) => num ** 2);
console.log(squaredNumbers); // [1, 4, 9, 16]
In Python, the equivalent of map() is a built-in function that applies a given function to each item in an iterable (such as a list or dictionary). For example, let’s say we want to convert a list of strings to uppercase:
words = ['apple', 'banana', 'cherry']
uppercase_words = list(map(str.upper, words))
print(uppercase_words) # ['APPLE', 'BANANA', 'CHERRY']
There is no such thing as a map function in VBA. This time, let's take a simple example and learn how to create a map function in VBA.
Sub demoMap()
'demo to convert a list of strings to uppercase
Dim Words
Dim uppercase_words
Words = Array("apple", "banana", "cherry")
uppercase_words = map("upper", Words)
Dim i As Long
For i = LBound(uppercase_words) To UBound(uppercase_words)
Debug.Print uppercase_words(i)
Next
End Sub
Function upper(str As String) As String
upper = UCase(str)
End Function
Function map(f As String, A As Variant) As Variant
'assumes that A is a 1-dimensional variant array
'and f is the name of a function that can be applied to it
Dim i As Long
Dim M As Variant
ReDim M(LBound(A) To UBound(A))
For i = LBound(A) To UBound(A)
M(i) = Application.Run(f, A(i))
Next
map = M
End Function
The demoMap procedure entered lowercase words in the Words array. And the upper function and Words, which change lowercase letters to uppercase letters in the map function, are sheared as parameters.
The upper function uses a built-in function UCASE that changes to capital letters to return the string.
The most important thing is the map function. The map function receives the function name and the one-dimensional array as parameters. The first thing the map function does is to create an array that is the same size as the received array. And it will store the result value in the newly created array. Running a function passed in a string is the Run function of the application object. In fact, this function uses the received function name as a function and passes the parameters received together to the function to obtain the result of the operation.