Added lume.wordwrap(); updated README.md and tests

This commit is contained in:
rxi 2015-01-10 20:26:19 +00:00
parent 9b5abf3d58
commit 756d30416d
3 changed files with 45 additions and 0 deletions

View File

@ -316,6 +316,15 @@ instead of whitespace.
lume.trim(" Hello ") -- Returns "Hello"
```
### lume.wordwrap(str [, limit])
Returns `str` wrapped to `limit` number of characters per line, by default
`limit` is `72`. `limit` can also be a function which when passed a string,
returns `true` if it is too long for a single line.
```lua
-- Returns "Hello world\nThis is a\nshort string"
lume.wordwrap("Hello world. This is a short string", 14)
```
### lume.format(str [, vars])
Returns a formatted string. The values of keys in the table `vars` can be
inserted into the string by using the form `"{key}"` in `str`; numerical keys

View File

@ -480,6 +480,32 @@ function lume.trim(str, chars)
end
function lume.wordwrap(str, limit)
limit = limit or 72
local check
if type(limit) == "number" then
check = function(str) return #str >= limit end
else
check = limit
end
local rtn = {}
for j, line in ipairs(lume.split(str, "\n")) do
local str
for i, word in ipairs(lume.split(line)) do
local s = (str and (str .. " ") or "") .. word
if check(s) then
rtn[#rtn + 1] = str
str = word
else
str = s
end
end
rtn[#rtn + 1] = str
end
return table.concat(rtn, "\n")
end
function lume.format(str, vars)
if not vars then return str end
local f = function(x)

View File

@ -431,6 +431,16 @@ tests["lume.trim"] = function()
testeq( lume.trim("^.hello world]^", "^.]"), "hello world" )
end
-- lume.wordwrap
tests["lume.wordwrap"] = function()
local str = "A small string with some words and then some more words"
local b = "A small string with\nsome words and then\nsome more words"
local fn = function(str) return #str >= 20 end
testeq( lume.wordwrap(str), str )
testeq( lume.wordwrap(str, 20), b )
testeq( lume.wordwrap(str, fn), b )
end
-- lume.format
tests["lume.format"] = function()
local str = lume.format("a {a} in a {b}", {a = "mouse", b = "house"})