Now that we have this nice little DistanceFinder, let’s work out how to create one that we can use.
DistanceFinder, as it stands now, accepts an input array of pairs, each pair consisting of a length and an arbitrary object to be returned if the finder finds it. Let’s write a test, like the ones we have, but returning the correct L_Bezier in a batch.
This is almost not worth doing, other than to show how to do it. At this instant, I’m not even sure whether we’ll have a batch of L_Beziers to give it, or if they’ll come along one by one somehow. I guess I’ll try both ways.
function Tests:test_incremental_add()
local df = DistanceFinder()
local b = self:sample_bezier()
local lb1 = b:linearized(3)
df:add(lb1.length, lb1)
local lb2 = b:linearized(3)
df:add(lb1.length, lb2)
local l2 = lb1.length/2
local rem, val = df:find(l2)
self:assert_equals(rem, l2, "1")
self:assert_equals(val, lb1, "1")
rem, val = df:find(3*l2)
self:assert_equals(rem, l2, "2")
self:assert_equals(val, lb2, "2")
end
That passes with these changes:
DistanceFinder = class()
function DistanceFinder:init(pairs)
self._pairs = pairs or {}
self:check_pairs(pairs)
end
function DistanceFinder:add(length, obj)
table.insert(self._pairs, {length, obj})
self._total_length += length
end
With that in place, we can change this:
function DistanceFinder:check_pairs()
self._total_length = 0
for _, pair in self._pairs do
self._total_length += pair[1]
end
end
And adjust the init, to this:
DistanceFinder = class()
function DistanceFinder:init(pairs)
self._pairs = {}
self:check_pairs(pairs or {})
end
function DistanceFinder:check_pairs(pairs)
self._total_length = 0
for _, pair in pairs do
self:add(pair[1], pair[2])
end
end
function DistanceFinder:add(length, obj)
table.insert(self._pairs, {length, obj})
self._total_length += length
end
I think it’s good practice, if we have an incremental way of building the object, to either have the creation method call that or vice versa. In this case we’ll have our creator call the add. The code is a bit tricksy but I think it is OK for now. Might refine later.
Is it worth it to create the array and pass it in, given that we have a batch of L_Beziers? I don’t think so. It is storming here, I’ll stop
We take small steps, making things better. After a while, things are pretty good.
Safe paths!