Range.purs 1.41 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 14
derive instance newtypeClosed :: Newtype (Closed t) _

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

19 20
type NumberRange = Closed Number

21
range :: NumberRange -> Number
22 23 24 25
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
26 27
normalise :: NumberRange -> Number -> Number
normalise r@(Closed {min}) v = (clamp r v - min) / range r
28 29 30

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

34
-- | A closed range between 0 and 1
35
closedProbability :: NumberRange
36 37
closedProbability = Closed { min: 0.0, max: 1.0 }

38 39 40 41 42 43 44 45
-- | 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 }