This Blog post describes String as Collections. Strings are being treated as a sequence of Characters and so operations like ArrayAccess/Slicing and Member functions can be applied on a String Object.
Strings as Collections: Strings are being treated as sequence of Characters in most of the languages, ColdFusion 2018 Update 2 exposed a functionality where-in Strings were treated as sequence of Character and a developer was able to invoke array like operations eg: str[i] or str[start:end:step] i.e slices like operations on Strings. So the code-snippets like the following were perfectly valid.
<
cfscript
>
str =
"Hello World"
;
WriteOutput
(str[7]); // will output W
WriteOutput
(
"<br>"
);
WriteDump(str[1:11:2]); // will output HloWrd
</
cfscript
>
While this functionality was implemented, their arose a need that since Strings are being exposed as sequence of Characters, CFML developers should be able to leverage meaningful functional abilities which are available in Array functions as well.In this release we have exposed functions which can be invoked on Strings by treating Strings as stream of Characters.
The following functions have been implemented in Project Stratus (ColdFusion 2021) release.
- Every
- Filter
- Map
- Reduce
- Some
- Sort
The functional usage can be shown by the examples:
- Every
<
cfscript
>
myStr=
"HELLO WORLD"
;
callback=(value)=>{
return value<125;
}
writeOutput
(myStr.every(callback));
</
cfscript
>
- Filter
<
cfscript
>
myStr=
"123456789"
;
writeOutput
(myStr.filter(function(num){
return num>53;
})); //Returns a list of
all
numbers greater than 5
writeOutput
(
"<br>"
)
</
cfscript
>
<!---
The code-snippet written above will output:
6789 as the asci valueof '6' is 54, so all numbers
greater than 5 should qualify for the filter function.
--->
- Map
<
cfscript
>
myStr=
"123456789"
;
closure=function(item){
return item+5;
}
writeOutput
(myStr.map(closure));
writeOutput
(
"<br>"
)
</
cfscript
>
<!---
The code-snippet above will output:
54 55 56 57 58 59 60 61 62 as it adds 5 to the asci value of each
character and asci-value of 1 is 49
--->
- Reduce
<
cfscript
>
myStr=
"23548798113591"
;
closure=function(value1,value2){
return (value1+value2/2); // Calculates the average of the values
in
the list
}
writeOutput
(myStr.reduce(closure,0));
writeOutput
(
"<br>"
)
</
cfscript
>
<!---
The code-snippet shown above will output:
369.0 after computing the average of the
asci value of all numbers.
--->
- Some
<
cfscript
>
myList=
"123456789"
;
writeDump(myList.
some
(function(num){
return num>53;
}));
writeOutput
(
"<br>"
)
</
cfscript
>
- Sort
<
cfscript
>
myList=
"987654321"
;
writeDump(myList.sort());
writeOutput
(
"<br>"
)
</
cfscript
>
You must be logged in to post a comment.