sup

A curses threads-with-tags style email client

sup.git

git clone https://supmua.dev/git/sup/
commit 5e222ea3d894b6cf0803934384288c45b1d4856a
parent 6b24e17f519db65727f967f49e6ec7b146c88e50
Author: Whyme Lyu <callme5long@gmail.com>
Date:   Sun, 30 Jun 2013 15:56:38 +0800

Implement String#slice_by_display_length

Diffstat:
M lib/sup/util.rb | 7 +++++++
M test/unit/util/string.rb | 16 ++++++++++++++++
2 files changed, 23 insertions(+), 0 deletions(-)
diff --git a/lib/sup/util.rb b/lib/sup/util.rb
@@ -259,6 +259,13 @@ class String
     @display_length ||= Unicode.width(self, false)
   end
 
+  def slice_by_display_length len
+    each_char.each_with_object "" do |c, buffer|
+      len -= c.display_length
+      buffer << c if len >= 0
+    end
+  end
+
   def camel_to_hyphy
     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
   end
diff --git a/test/unit/util/string.rb b/test/unit/util/string.rb
@@ -20,4 +20,20 @@ describe "Sup's String extension" do
       end
     end
   end
+
+  describe "#slice_by_display_length(len)" do
+    let :data do
+      [
+        ['some words', 6, 'some w'],
+        ['中文', 2, '中'],
+        ['älpha', 3, 'älp'],
+      ]
+    end
+
+    it "slices string by display length" do
+      data.each do |(str, length, sliced)|
+        str.slice_by_display_length(length).must_equal sliced
+      end
+    end
+  end
 end