Function progression. Intended for amusement.
- Posted by xecronix
1 week ago
This works. I swear.
-- Not pretty... but it works. I'll probably throw
-- this one away. But for today, it lives.
-- Sequence retval will be at least and no more than
-- len characters long. if length(s) < len the
-- difference will be right padded with spaces.
-- If s > len then retval will be a truncated
-- version of s.
function fixed_len(sequence s, integer len)
sequence retval = ""
integer i = 1
while i < length(s) + 1 do
retval = sprintf("%s%s", {retval,s[i]})
i += 1
end while
while i < len + 1 do
retval = sprintf("%s%s", {retval," "})
i += 1
end while
return retval
end function
Better. I could have stopped, but I didn't.
function fixed_len(sequence s, integer len)
sequence retval = repeat(" ", len)
integer i = 1
while i <= length(s) and i <= len do
retval[i] = mid(s, i, 1)
i+=1
end while
return join(retval, "")
end function
It doesn't look like much of a change. Probably significantly better than the last one.
function fixed_len(sequence s, integer len)
sequence retval = repeat(' ', len)
integer i = 1
while i <= length(s) and i <= len do
retval[i] = s[i]
i+=1
end while
return retval
end function
This is probably the best version so far, IMHO
function fixed_len(sequence s, integer len)
if length(s) < len then
return s & repeat(' ', len - length(s))
end if
return s[1..len]
end function
ChatGPT wrote this one. It looks like it should work but, it's as ugly as the first one, I think.
function fixed_len(sequence s, integer len)
return s[1..min(length(s), len)] & repeat(' ', max(0, len - length(s)))
end function
Better Code Step by Step
Not Categorized, Please Help
|
|