Find the intersection of two lines: Difference between revisions

Content deleted Content added
Hout (talk | contribs)
Hout (talk | contribs)
m →‎JS ES6: Slight reorganisation
Line 613: Line 613:
===ES6===
===ES6===
<lang JavaScript>(() => {
<lang JavaScript>(() => {
'use strict';
// INTERSECTION OF TWO LINES ----------------------------------------------
// INTERSECTION OF TWO LINES ----------------------------------------------


// intersection :: Line -> Line -> Either String (Float, Float)
// intersection :: Line -> Line -> Either String (Float, Float)
const intersection = ([
const intersection = (ab, pq) => {
[ax, ay],
[bx, by]
], [
[px, py],
[qx, qy]
]) => {
const
const
abDX = ax - bx,
delta = f => x => f(fst(x)) - f(snd(x)),
pqDX = px - qx,
[abDX, pqDX, abDY, pqDY] = apList(
abDY = ay - by,
[delta(fst), delta(snd)], [ab, pq]
pqDY = py - qy,
),
determinant = abDX * pqDY - abDY * pqDX;
determinant = abDX * pqDY - abDY * pqDX;


return determinant !== 0 ? Right((() => {
return determinant !== 0 ? Right((() => {
const
const [abD, pqD] = map(
abD = ax * by - ay * bx,
([a, b]) => fst(a) * snd(b) - fst(b) * snd(a),
pqD = px * qy - py * qx;
[ab, pq]
);
return apList(
return apList(
[([pq, ab]) =>
[([pq, ab]) =>
Line 664: Line 660:
[].concat.apply([], fs.map(f => //
[].concat.apply([], fs.map(f => //
[].concat.apply([], xs.map(x => [f(x)]))));
[].concat.apply([], xs.map(x => [f(x)]))));

// fst :: (a, b) -> a
const fst = tpl => tpl[0];

// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);

// snd :: (a, b) -> b
const snd = tpl => tpl[1];


// show :: a -> String
// show :: a -> String
const show = x => JSON.stringify(x); //, null, 2);
const show = x => JSON.stringify(x); //, null, 2);



// TEST -------------------------------------------------------------------
// TEST --------------------------------------------------


// lrIntersection ::Either String Point
// lrIntersection ::Either String Point
Line 678: Line 684:
[10.0, 7.0]
[10.0, 7.0]
]);
]);

return show(lrIntersection.Left || lrIntersection.Right);
return show(lrIntersection.Left || lrIntersection.Right);
})();</lang>
})();</lang>