Module:Join

From Pittsburgh Streets

Documentation for this module may be created at Module:Join/doc

local p = {};

function p.join(frame)
  -- Arguments passed to the parent template.
  local parent_args = frame:getParent().args;

  -- Separators.
  local sep = parent_args['sep'] or ', ';
  local penult = parent_args['penult'] or sep;
  local two_sep = parent_args['two-sep'] or penult;

  -- Count nonempty arguments.
  local i = 1;
  local nonempty_arg_count = 0;
  while parent_args[i] do
    if parent_args[i] ~= '' then
      nonempty_arg_count = nonempty_arg_count + 1;
    end
    i = i + 1;
  end

  -- Join pieces.
  local result = '';
  local i = 1;
  local nonempty_args_done = 0;
  while nonempty_args_done < nonempty_arg_count do
    if parent_args[i] ~= '' then
      if nonempty_args_done > 0 then
        if nonempty_arg_count == 2 then
          result = result .. two_sep
        elseif nonempty_args_done == nonempty_arg_count - 1 then
          result = result .. penult
        else
          result = result .. sep
        end
      end
      result = result .. parent_args[i];
      nonempty_args_done = nonempty_args_done + 1;
    end
    i = i + 1;
  end

  return result;
end

return p;