How to get absolute value from animated value in react native?

Viewed 1224

Let's suppose I have an animated value pan.y which is equal to -3. How can I get the absolute value from -3, which is 3.

I tried Animated.modulos(pan.y, 1) and it didn't work. I do not know why there is a second argument in this function.

Like it says in the docs:

static modulo(a, modulus)

Creates a new Animated value that is the (non-negative) modulo of the provided Animated value

here is the link:

https://reactnative.dev/docs/animated#modulo

3 Answers

It's a bit late, but I also needed to take the abs of an Animated.Value in order to implement max between 2 Animated.Values so hopefully this helps anyone else who is trying to do this.

To give more context on the question, the reason why Animated.modulus doesn't work here is since the modulus is equivalent of x % y. For example, -2.3 % 1 = 0.7 (so although this value is positive, it doesn't give you what you need.

The general idea on calculating the abs value of an Animated.Value is taking some value a and it's negation -a, and clamping them between 0 and inf. This way, you'll end up with two values that is the absolute value and 0. Then you can simply add them.

It looks like this:

function abs(a) {
  const b = Animated.multiply(a, -1);
  const clampedA = Animated.diffClamp(a, 0, Number.MAX_SAFE_INTEGER);
  const clampedB = Animated.diffClamp(b, 0, Number.MAX_SAFE_INTEGER);

  return Animated.add(clampedA, clampedB);
};

With absolute value, then it's easy to implement both max and min functions with: max(r,s) = 0.5 * (r + s + |r-s|) and min(r,s) = 0.5 * (r + s - |r-s|).

The equivalent javascript code (where abs is the method above):

function max(a, b) {
  return Animated.multiply(
    0.5,
    Animated.add(Animated.add(a, b), abs(Animated.subtract(a, b)))
  );
};

function min(a, b) {
  return Animated.multiply(
    0.5,
    Animated.subtract(Animated.add(a, b), abs(Animated.subtract(a, b)))
  );
};

If the range of your value is finite and known, you can also use interpolate to get the absolute value. For example, to get the absolute value of a given that it's always between [-120, 120]:

a.interpolate({
    inputRange: [-120, 0, 120],
    outputRange: [120, 0, 120]
})

In javascript you can use Math.abs but I am not sure if it will work

Related