Reduces an array to a single value
Device + Agent
Name | Type | Description |
---|---|---|
function | Function |
A reduction function
|
Any Squirrel data type
This method applies the supplied function to all of the items in the target array, starting with the first two. The function returns a single value which is then combined with the next (third) item in the array — and so on until all of the items have been combined into a single value which the method returns.
The reduction function must include two parameters: the result returned by its previous iteration and the next item in the array — reduce() takes care of iterating through the target array’s items.
If the target array contains just a single item, that item will be the value that is returned. If the target contains no items, reduce() will return null
.
The example below shows the use of reduce() to add the elements of the array sourceArray. The function used to perform the reduction can be simplified further if we use a Squirrel lambda function, and this is shown in the second example.
The third example shows how reduce() can be used on an array of string segments (generated by splitting a source string into sub-strings separated by a newline) to reassemble the string after processing.
local sourceArray = [10, 21, 30, 43]; | |
// Combine all the values in the array | |
local reduction = sourceArray.reduce(function(previousValue, currentValue){ | |
return (previousValue + currentValue); | |
}); | |
server.log(reduction); | |
// Displays "104" |
local sourceArray = [10, 21, 30, 43]; | |
// Combine all the values in the array | |
local reduction = sourceArray.reduce(@(p, c) p + c); | |
server.log(reduction); | |
// Displays "104" |
// Decode an X.509 certificate .pem file | |
// Remove the armor, concatenate the lines and base64 decode the text | |
function decodePem(pemString) { | |
local lines = split(pemString, "\n"); | |
// We really ought to iterate over the array until we find a starting line, | |
// and then look for the matching ending line, rather than assuming its on line 0 | |
if ((lines[0] == "-----BEGIN PRIVATE KEY-----" && | |
lines[lines.len() - 1] == "-----END PRIVATE KEY-----") || | |
(lines[0] == "-----BEGIN RSA PRIVATE KEY-----" && | |
lines[lines.len() - 1] == "-----END RSA PRIVATE KEY-----") || | |
(lines[0] == "-----BEGIN PUBLIC KEY-----" && | |
lines[lines.len() - 1] == "-----END PUBLIC KEY-----")) { | |
local all = lines.slice(1, lines.len() - 1).reduce(@(a, b) a + b); | |
return http.base64decode(all); | |
} | |
return null; | |
} |