Range.purs 1.49 KB
Newer Older
1
module Gargantext.Utils.Range where
2

3
import Prelude hiding (clamp)
4
import Data.Newtype (class Newtype)
5 6 7 8 9 10 11 12

class Range r v where
  clamp :: r -> v -> v
  within :: r -> v -> Boolean

-- | A Closed Interval, in math speak
newtype Closed t = Closed { min :: t, max :: t }

13
derive instance Newtype (Closed t) _
14

15
instance Ord t => Range (Closed t) t where
16
  clamp (Closed r) = max r.min <<< min r.max
17
  within (Closed r) v = (r.min <= v) && (v <= r.max)
18

19
instance Eq t => Eq (Closed t) where
20 21
  eq (Closed r1) (Closed r2) = (r1.min == r2.min) && (r1.max == r2.max)

22 23
type NumberRange = Closed Number

24
range :: NumberRange -> Number
25 26 27 28
range (Closed r) = r.max - r.min

-- | Clamps the value to within the range and returns a normalised
-- | (0-1) float indication progress along the range
29 30
normalise :: NumberRange -> Number -> Number
normalise r@(Closed {min}) v = (clamp r v - min) / range r
31 32 33

-- | Given a normal (0-1) float representing progress along a range,
-- | project it onto the range
34 35
projectNormal :: NumberRange -> Number -> Number
projectNormal r@(Closed {min}) v = (clamp closedProbability v * range r) + min
36

37
-- | A closed range between 0 and 1
38
closedProbability :: NumberRange
39 40
closedProbability = Closed { min: 0.0, max: 1.0 }

41 42 43 44 45 46 47
-- | Updates the minimum value in a closed range
withMin :: forall t. Closed t -> t -> Closed t
withMin (Closed {max}) min = Closed { min, max }

-- | Updates the maximum value in a closed range
withMax :: forall t. Closed t -> t -> Closed t
withMax (Closed {min}) max = Closed { min, max }