Last active
October 6, 2022 17:11
-
-
Save JamoCA/92ddc1d7cf04aa021321ba7e9185f16f to your computer and use it in GitHub Desktop.
justNumericList - Filters a text string to return int/float numeric values w/optional min/max restrictions. (ColdFusion / CFML)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfscript> | |
/* justNumericList - Filters a text string to return int/float numeric values w/optional min/max restrictions. | |
* 2022-10-06 | |
* GIST: https://gist.github.com/JamoCA/92ddc1d7cf04aa021321ba7e9185f16f | |
* Forked from https://cflib.org/udf/justNumericList by James Moberg / SunStar Media | |
* Refactor/modernized (CF2016+ or Lucee required); | |
* Parameters: | |
* @param nList List to filter. (Required) | |
* @param strDelim List delimiter. (default: ",") | |
* @param integersOnly Boolean to restrict returned list to only signed integers (default: false) | |
* @param minVal Numeric value to filter minimum values (default: no minimum) | |
* @param maxVal Numeric value to filter maximum values (default: no maximum) | |
*/ | |
public string function justNumericList( | |
required string nList, | |
string strDelim=",", | |
boolean integersOnly=false, | |
string minVal="", | |
string maxVal="" | |
) hint="Filters a text string to return int/float numeric values w/optional min/max restrictions" { | |
local.result = []; | |
local.min = (isnumeric(arguments.minVal)) ? val(arguments.minVal) : ""; | |
local.useMin = len(local.min); | |
local.max = (isnumeric(arguments.maxVal)) ? val(arguments.maxVal) : ""; | |
local.useMax = len(local.min); | |
arguments.strDelim = (len(arguments.strDelim)) ? arguments.strDelim : ","; | |
local.aryN = listtoarray(arguments.nlist, arguments.strDelim, false, true); | |
for (local.item in local.aryN) { | |
local.item = trim(local.item); | |
local.isMatch = isvalid("numeric", local.item) && (!compare(val(local.item), local.item)); | |
if (local.isMatch && arguments.integersOnly && !isvalid("integer", local.item)) local.isMatch = false; | |
if (local.isMatch && local.useMin && local.item lt local.min) local.isMatch = false; | |
if (local.isMatch && local.useMax && local.item gt local.max) local.isMatch = false; | |
if (local.isMatch) arrayappend(local.result, local.item); | |
} | |
return arraytolist(local.result, arguments.strDelim); | |
} | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment