Skip to content

Instantly share code, notes, and snippets.

@lrechert
Last active April 18, 2016 18:41
Show Gist options
  • Select an option

  • Save lrechert/e5cbb956061b60194b0b to your computer and use it in GitHub Desktop.

Select an option

Save lrechert/e5cbb956061b60194b0b to your computer and use it in GitHub Desktop.
Ruby Weekly Challenge - leftpad
# Description:
# From Programming Praxis ... https://programmingpraxis.com/2016/03/25/leftpad/
# Large portions of the internet failed a few days ago when a program called
# leftpad, which pads a string to a given length by adding spaces or other
# characters at the left of the string, was suddenly removed from its repository.
# The whole episode is sad, and brings nothing but shame on everyone involved
# (though everyone involved seems to think they acted properly throughout), and
# all of the web sites that broke were created by fools (you don’t rely on
# unknown third parties to maintain code critical to your application at some
# unknown place on the internet). You can read more about what happened at these
# links: good overview of what happened, Azer’s statement, NPM’s statement, and
# satire. The code that caused the problem is shown below:
# module.exports = leftpad;
#
# function leftpad (str, len, ch) {
# str = String(str);
#
# var i = -1;
#
# if (!ch && ch !== 0) ch = ' ';
#
# len = len - str.length;
#
# while (++i < len) {
# str = ch + str;
# }
#
# return str;
# }
# Your task is to write a proper version of leftpad; make sure yours operates in
# linear time instead of the quadratic time caused by the string concatenation in
# Azer’s code.
def pad_left(str, len, c=' ')
return str if str.nil? || len.nil? || len <= str.length || (c && c.length != 1)
c ||= ' '
"#{c*(len-str.length)}#{str}"
end
require_relative '../pad_left'
describe "#pad_left" do
context "when str is nil" do
it "returns nil" do
expect(pad_left(nil, 15, 'l')).to be_nil
end
end
context "when c is nil" do
it "returns str prefixed with ' '" do
expect(pad_left('lovely_lassy', 15, nil)).to eql ' lovely_lassy'
end
it "returns str prefixed with ' '" do
expect(pad_left('lovely_lassy', 15)).to eql ' lovely_lassy'
end
end
context "when len is nil" do
it "returns str" do
expect(pad_left('lovely_lassy', nil, 'l')).to eql 'lovely_lassy'
end
end
context "when len is <= the length of str" do
it "returns str" do
expect(pad_left('lovely_lassy', 5, 'l')).to eql 'lovely_lassy'
end
end
context "when c is more than one char" do
it "returns str" do
expect(pad_left('lovely_lassy', 15, 'lll')).to eql 'lovely_lassy'
end
end
context "when str is non-nil and len is > str.length" do
it "prefixes str with c's up to size = len" do
expect(pad_left('lovely_lassy', 15, 'l')).to eql 'llllovely_lassy'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment