Justify self in a space of length

left is the space ratio on the left side.

  • 0.0 for left-justified (no space at the left)
  • 1.0 for right-justified (all spaces at the left)
  • 0.5 for centered (half the spaces at the left)

char, or ' ' by default, is repeated to pad the empty space.

Examples

assert "hello".justify(10, 0.0)  == "hello     "
assert "hello".justify(10, 1.0)  == "     hello"
assert "hello".justify(10, 0.5)  == "  hello   "
assert "hello".justify(10, 0.5, '.') == "..hello..."

If length is not enough, self is returned as is.

assert "hello".justify(2, 0.0)   == "hello"

REQUIRE: left >= 0.0 and left <= 1.0

ENSURE: self.length <= length implies result.length == length

ENSURE: self.length >= length implies result == self

Property definitions

core $ Text :: justify
	# Justify `self` in a space of `length`
	#
	# `left` is the space ratio on the left side.
	# * 0.0 for left-justified (no space at the left)
	# * 1.0 for right-justified (all spaces at the left)
	# * 0.5 for centered (half the spaces at the left)
	#
	# `char`, or `' '` by default, is repeated to pad the empty space.
	#
	# Examples
	#
	# ~~~
	# assert "hello".justify(10, 0.0)  == "hello     "
	# assert "hello".justify(10, 1.0)  == "     hello"
	# assert "hello".justify(10, 0.5)  == "  hello   "
	# assert "hello".justify(10, 0.5, '.') == "..hello..."
	# ~~~
	#
	# If `length` is not enough, `self` is returned as is.
	#
	# ~~~
	# assert "hello".justify(2, 0.0)   == "hello"
	# ~~~
	#
	# REQUIRE: `left >= 0.0 and left <= 1.0`
	# ENSURE: `self.length <= length implies result.length == length`
	# ENSURE: `self.length >= length implies result == self`
	fun justify(length: Int, left: Float, char: nullable Char): String
	do
		var pad = (char or else ' ').to_s
		var diff = length - self.length
		if diff <= 0 then return to_s
		assert left >= 0.0 and left <= 1.0
		var before = (diff.to_f * left).to_i
		return pad * before + self + pad * (diff-before)
	end
lib/core/text/abstract_text.nit:561,2--596,4