diff --git a/README.md b/README.md index 4228db5..bdc43a8 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,18 @@ intersection_result = intersect_triangles(t1, t2) plot(intersection_result) ``` +```ruby +p1 = Point.new(2.2, 3.3) +p2 = Point.new(5.5, 6.6) +ls = LineSegment.new(p1,p2) +# find a length of a line segment based on two points +lenght = ls.length +# return straight line object +StraightLine sl = ls.to_straight_line + + +``` + ![triangles_example](docs/images/triangles_example.png) ![intersect_triangles_example](docs/images/intersect_triangles_example.png) diff --git a/lib/primitives/elementary/line_segment.rb b/lib/primitives/elementary/line_segment.rb index 00f4924..90e5d02 100644 --- a/lib/primitives/elementary/line_segment.rb +++ b/lib/primitives/elementary/line_segment.rb @@ -5,13 +5,31 @@ class LineSegment attr_reader :ends_at def initialize(begins_at, ends_at) - # Your code goes here... + check_is_a_point(begins_at) + check_is_a_point(ends_at) + @begins_at = begins_at + @ends_at = ends_at end + # Count a length of a line segment based on two points def length - # Your code goes here... - # REQUIREMENT: use lazy evaluation + @length ||= begins_at.distance ends_at end + + # Return straight line object based points coordinates + def to_straight_line + a = ends_at.y - begins_at.y + b = begins_at.x - ends_at.x + c = -begins_at.x * ends_at.y + begins_at.y * ends_at.x + StraightLine.new(a, b, c) + end + + private def check_is_a_point(x) + unless x.is_a? Point + fail TypeError.new "Invalid type of argument" + end + end + end end end diff --git a/test/elementary_test.rb b/test/elementary_test.rb index d41847c..f3b1d64 100644 --- a/test/elementary_test.rb +++ b/test/elementary_test.rb @@ -1,4 +1,4 @@ -require "test_helper" +require "./test/test_helper" class ElementaryTest < Minitest::Test include Primitives @@ -7,6 +7,7 @@ class ElementaryTest < Minitest::Test def setup @point = Elementary::Point.new(2.3, 5.1) + @line_segment = Elementary::LineSegment.new(Elementary::Point.new(2.2, 3.3),Elementary::Point.new(5.5, 6.6)) end def test_point_attributes_set_correctly_on_instance_create @@ -42,4 +43,14 @@ def test_move_method_doesnt_affect_point_instance_on_which_it_was_applied assert_in_delta 2.3, original.x, @@delta assert_in_delta 5.1, original.y, @@delta end + + def test_line_length + length = @line_segment.length + assert_in_delta 4.66690, length, @@delta + end + + def test_to_straight_line + # test will be added when straight line class is approved + end + end