\$\begingroup\$
\$\endgroup\$
4
I have created a named function with signature PadInternal(base, width, paddingStr)
where:
base
is a string you want to add padding towidth
is the length of the individual chunkspaddingStr
is the string to pad with
called from a cell like: Calling from cell
PadInternal("Hello", 1, " ") = "H e l l o"
PadInternal("World", 3, "**") = "Wor**ld"
And here's the function:
Tag | Description |
---|---|
Name | PadInternal |
Scope | Workbook |
Comment | base : a string you want to add padding to | width : the length of the individual chunks | paddingStr : the string to pad with |
Refers To | =LAMBDA(base,width,paddingStr, IF(LEN(base)<=width, base, LET(LHS, LEFT(base, width), RHS, RIGHT(base, LEN(base) - width), LHS & paddingStr & PadInternal(RHS,width,paddingStr)))) |
=LAMBDA(
base,
width,
paddingStr,
IF(
LEN(
base
) <= width,
base,
LET(
LHS,
LEFT(
base,
width
),
RHS,
RIGHT(
base,
LEN(
base
) - width
),
LHS & paddingStr &
PadInternal(
RHS,
width,
paddingStr
)
)
)
)
Questions
As this is my first time using recursive Lambda functions in Excel, I'd like some feedback. In particular:
- Is my algorithm efficient - I was thinking something with
TEXTJOIN
may be faster? - How could this be improved to take a dynamic array as "base"?
- Can I have default values for the arguments?
- What about meta data (formatting of the tooltip, scope etc), are there other ways to make my function more accessible?
asked Dec 16, 2020 at 19:25
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
I thought about this for a while and came up with some (what I think are) improvements:
=LAMBDA(base,width,paddingStr,TEXTJOIN(paddingStr,,MID(base,SEQUENCE((LEN(base)/width)+1,,1,width),width)))
This would:
- No longer require a recursive
LAMBDA()
which should prove to be faster (untested) - Uses
TEXTJOIN()
which can handle errors and empty values internally so there is no longer any worry about that. - The use of
MID()
negates the use ofLEFT()
,RIGHT()
etc. - No longer be using
LET()
which may also be using internal memory.
-
1\$\begingroup\$ With the risk of appearing pedantic, a slight improvement would be to replace the
+1
with+0.5
so that when the length is an even number the sequence does not generate an extra index which would be larger than the length thus resulting in an extra blank string to be joined. Nice solution! \$\endgroup\$Cristian Buse– Cristian Buse2021年01月06日 15:21:42 +00:00Commented Jan 6, 2021 at 15:21
default
ChunkMyText
might do. :) \$\endgroup\$