what is animationTimingFunction in vivus.js - javascript

I was just going through the source of vivus.js and came across the followng like of code:
currentFrame = this.animTimingFunction(this.currentFrame / this.frameLength) * this.frameLength;
Now this function call can be seen HERE.
The only other place this is defined in is below:
this.animTimingFunction = options.animTimingFunction || Vivus.LINEAR;
This can be seen on the repo HERE.
Now my question is , why is this.animTimingFunction being called as a function when it actually is not a function ? can anybody explain ?
Thank you.

But it is a function as mentioned in the code comments
animTimingFunction <function> timing animation function for the complete SVG`
From the code it is one of the options that can be passed to the Vivus constructor. Predefined timing functions are defined at line 66
/**
* Timing functions
**************************************
*
* Default functions to help developers.
* It always take a number as parameter (between 0 to 1) then
* return a number (between 0 and 1)
*/
Vivus.LINEAR = function (x) {return x;};
Vivus.EASE = function (x) {return -Math.cos(x * Math.PI) / 2 + 0.5;};
Vivus.EASE_OUT = function (x) {return 1 - Math.pow(1-x, 3);};
Vivus.EASE_IN = function (x) {return Math.pow(x, 3);};
Vivus.EASE_OUT_BOUNCE = function (x) {
var base = -Math.cos(x * (0.5 * Math.PI)) + 1,
rate = Math.pow(base,1.5),
rateR = Math.pow(1 - x, 2),
progress = -Math.abs(Math.cos(rate * (2.5 * Math.PI) )) + 1;
return (1- rateR) + (progress * rateR);
};
On line 204
this.animTimingFunction = options.animTimingFunction || Vivus.LINEAR;
you can see that it either uses the passed function or when nothing is set for animTimingFunction a default function defined at Vivus.LINEAR
So you can not pass a function, pass one of the predefined functions, or pass your own timing function:
Vivus(...,{},...);
//OR
Vivus(...,{
animTimingFunction:Vivus.EASE
},...);
//OR
Vivus(...,{
animTimingFunction:Vivus.EASE_OUT
},...);
//OR
Vivus(...,{
//custom function
//input number between 0 and 1
//output number between 0 and 1
animTimingFunction:function(x){
//manipulate x as needed and return the new number
}
},...);

Related

Dont understand the next iteration for recursion

I'm learning to work with recursion and so far it went well with basic examples. However I want to calculate the factorial, but I don't understand what happened step-by-step. If I do it imperatively I understand it but I fail on this example:
return x * fac(x-1); gives me back 5 * 4, so far soo good, but what happens now? Does it mean it become 20 now? So my next iteration would be then 20 * 19?
const fac = (x) => {
if(x <= 1) {
return x;
}
return x * fac(x-1);
};
console.log(fac(5)); // 120
just walk through the logic.
1. fac(5) yields 5 * fac(4)
2. fac(4) yields 4 * fac(3)
3. fac(3) yields 3 * fac(2)
4. fac(2) yields 2 * fac(1)
5. fac(1) yields 1
substituting from bottom to top, you get
fac(5) = 5 * 4 * 3 * 2 * 1
I think i understand that part now and the difference between 4 and fac(4). The steps look like:
5. 5 * // ()
4. 4 * // (20)
3. 3 * // (60)
2. 2 * // (120)
1. 1 * // (120)
However, I have another example which i cant resolve step by step, while i can see the logic in the imperatively programming.
let fibo = (x) => {
if(x<=2) {return 1;}
return fibo(x-1) + fibo(x-2);
};
console.log(fibo(4)); //3
I cant resolve step by step what return fibo(x-1) + fibo(x-2); values this gives me each step. On the imperatively programming it is
function fibonacci(num){
var a = 1, b = 0, temp;
while (num >= 1){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
console.log(fibonacci(4); // 3
where the steps would be like
4. b = 1
3. b = 1
2. b = 2
1. b = 3

can i reduce my code using loop for varaible or array

now the repeating code problem has been solved but when executed the if condition function of moveHorse is being executed repeteadly. please help.
function moveHorse(horseId)
);
interval=setInterval(function(){moveHorse('horseID');},20);
}
now the repeating code problem has been solved but when executed the if condition function of moveHorse is being executed repeteadly. please help.
Pass in the element ID as the function parameter, then you can refactor the code to -
// TODO: rename your local variable name because now it doesn't need to be horse4, right?
function horseUp(horseElementId) {
var horse = document.getElementById(horseElementId);
// do the rest
}
function horseDown(horseElementId) {
var horse = document.getElementById(horseElementId);
// do the rest
}
function horseleft(horseElementId) {
var horse = document.getElementById(horseElementId);
// do the rest
}
To use the function, pass in the element Id
horseUp('horse4');
horseLeft('horse2');
and so on
Since the only part that appears to be different is the horse being changed, just pass that in. For example:
var horse4 = document.getElementById('horse4');
function horseUp(horse, moving) {
var horseTop = horse.offsetTop;
var random = Math.random() * 2.7 + 2;
horse.style.top = horseTop - 0.5 * random + 'px';
if (horseTop <= window.innerHeight * 0.05) {
clearInterval(interval4);
interval4 = setInterval(moving, 10);
}
}
There's a few other variables like interval4 that you'll need to figure out, but this should give you the general idea.
May use OOP:
function Horse(id) {
this.el = document.getElementById(id);
}
Horse.prototype={
move(x,y){
this.el.offsetTop+=(this.y=typeof y !=="undefined"?y:this.y);
this.el.offsetLeft+=(this.x=typeof x !== "undefined"?x:this.x);
},
up(){
this.move(0,0.5*Math.random() * 2.7 + 2* + 'px';
},
down(){ this.move(0,- 0.5* Math.random() * 2.4 + 2);},
left(){ this.move(0.5* Math.random() * 2.4 + 2,0);},
right(){ this.move(- 0.5* Math.random() * 2.4 + 2,0);},
setInterval(){
this.interval=setInterval(_=>this.move(),10);
}
}
use like this:
var horse4=new Horse("horse4");
horse4.setInterval();
horse4.left();

How to obtain inverse result of d3-ease interpolation? [duplicate]

With d3.js we can achieve eased time out of normalized time t, typically in the range [0,1]
For example:
d3.easeCubic(0.25) = 0.0625
How can we reverse that, how can we find x given known y ?
d3.easeCubic(X) = 0.0625,
X ???
The answer here is cubic root, but still.
The problem is in reusability, ease function can change to d3.easeExpIn, or `d3.easeCircleOut, or any other, do you need to invent reverse functions on your own, or are they hidden anywhere ?
Firstly, your math is wrong. d3.easeCubic(0.25) will give you 0.0625:
var easy = d3.easeCubic(0.25);
console.log(easy);
<script src="https://d3js.org/d3.v4.min.js"></script>
Now, back to your question:
How can we reverse that, how can we find x given known y?
There is no native solution, but we can create our own function to find X given a known Y. The problem, of course, is that we have to invert the math for each specific easing... But, since you asked about d3.easeCubic, which is the same of d3.easeCubicInOut, let's try to create an inverted function for that particular easing.
First step, let's have a look at the source code:
export function cubicInOut(t) {
return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}
You can easily see that this is the correct function, giving us the same value as the first snippet:
function cubicInOut(t) {
return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}
console.log(cubicInOut(0.25))
Now, let's try to invert it.
The math here is somehow complicated, but for values less than 1, here is the function:
function inverseEaseCubic(t){
return Math.cbrt(t * 2) / 2;
}
And here is the demo. We pass 0.0625 to the function, and it returns 0.25:
function inverseEaseCubic(t){
return Math.cbrt(t * 2) / 2;
}
console.log(inverseEaseCubic(0.0625))
If you want to deal with numbers bigger than 1, this is the complete function:
function InverseEaseCubic(t){
return t <= 1 ? Math.cbrt(t * 2) / 2 : (Math.cbrt(2 * t - 2) + 2) / 2;
}
PS: In his comment, #altocumulus just reminded us that, sometimes, it's even impossible to find the value. Here is a very simple example. Suppose this function:
function exponentiation(a){
return a*a;
}
Now imagine that, when called with an unknown argument, the function returned 4. What's the argument? Can we find out? Impossible to determine, because second degree equations, like this one, have 2 roots:
console.log(exponentiation(2))//returns 4
console.log(exponentiation(-2))//also returns 4
I used the #Gerardo Furtado answer but the inverse function didn't work well so I wrote another
function cubicInOut(t) {
return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}
function inverseEaseCubic(x) {
return x < .5 ? Math.cbrt(x / 4) : (2 - Math.cbrt(2 - 2 * x)) / 2;
}
console.log(inverseEaseCubic(cubicInOut(1)) === 1);
console.log(inverseEaseCubic(cubicInOut(0.6)) === 0.6);
console.log(inverseEaseCubic(cubicInOut(0.4)) === 0.4);
console.log(inverseEaseCubic(cubicInOut(0.1)) === 0.1);
console.log(inverseEaseCubic(cubicInOut(0)) === 0);

JavaScript - Factorial explanation

I wanted someone to basically help me understand what each line of code is doing and help me comment each line (if applicable) so that it can help explain to another person what it's doing. It'd be awesome if one can just give second eyes and ensure that the code is actually good - I'm trying to get my head around Factorial/Recursion, and did some research and found these solutions for this.
I was given this scenario:
For positive n, factorial is n! = n(n−1)!   (e.g. 5! = 5 * 4
* 3 * 2 * 1)*
Here's what I've found for this scenario:
// Prompt user to enter a number to calculate the factorial
var num = prompt("What number do you want to find the factorial of?");
var factorial = function(n) {
if (n == 0) {
return 1;
} else {
product = 1;
for (i = 1; i < n; i++) {
product *= i;
}
return product;
}
}
console.log(factorial(num));
Recursive
Create a recursive algorithm to calculate the factorial using every second
number as shown in examples below:
5! = 5 * 3 * 1 = 15
6! = 6 * 4 * 2 = 48
As for the cursive part, this is added onto the above code and is written in the following -
//  recursive
var factorial = function(n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(num));
Would appreciate your assistance on this - Apologies if this has already been answered, please direct me to another thread if this has been already posted. Thanks!
You don't need recursion for that:
/**
* Calculate factorial, optionally using a difference other than 1 with previous value.
* Example: factorial(6, 2) // 6*4*2 = 48
*/
var factorial = function(n, d) {
if (!d) {d = 1;}
var product = 1;
while (n > 1) {
product *= n;
n -= d;
}
return product;
};
console.log(factorial(6, 2)); // 48
console.log(factorial(6)); // 720
Note: Declare local variables inside the function with keyword 'var'. Otherwise they become globals and the second time you attempt to use a function may produce wrong results.
Usually, writing a function for Factorial is an exercise on writing recursive function. The first example code is not recursive and just an overly complicated way of calculating a factorial by multiplying the numbers iteratively so I'll skip that.
The second code is recursive, and it is following the recursive definition of factorial in your usual mathematics:
f: N => N, f(x) = x! = { x < 1 : 1, else : x (x - 1)! }
Or equivalently in JavaScript:
let fac = n => n < 1 ? 1 : n * fac(n - 1);
An expansion of an example computation would look like:
5!
5(4!)
5(4(3!))
5(4(3(2!)))
5(4(3(2(1))))
5(4(3(2(1(0!)))))
5(4(3(2(1(1)))))
120

How to translate this bit of Python to idiomatic Javascript

My code so far:
// The q constant of the Glicko system.
var q = Math.log(10) / 400;
function Player(rating, rd) {
this.rating = rating || 1500;
this.rd = rd || 200;
}
Player.prototype.preRatingRD = function(this, t, c) {
// Set default values of t and c
this.t = t || 1;
this.c = c || 63.2;
// Calculate the new rating deviation
this.rd = Math.sqrt(Math.pow(this.rd, 2) + (Math.pow(c, 2) * t));
// Ensure RD doesn't rise above that of an unrated player
this.rd = Math.min(this.rd, 350);
// Ensure RD doesn't drop too low so that rating can still change
// appreciably
this.rd = Math.max(this.rd, 30);
};
Player.prototype.g = function(this, rd) {
return 1 / Math.sqrt(1 + 3 * Math.pow(q, 2) * Math.pow(rd, 2) / Math.pow(Math.PI, 2));
};
Player.prototype.e = function(this, p2rating, p2rd) {
return 1 / (1 + Math.pow(10, (-1 * this.g(p2rd) * (this.rating - p2rating) / 400)));
};
I'm working on a JS/HTML implementation of the Glicko rating system and am heavily borrowing from pyglicko -- which is to say, completely ripping it off.
It's rather short (probably less than 100 LoC without comments) but I'm having my misgivings about whether my translation will work because honestly, I have no idea how Javascript scoping and this actually work. You can see what I have at the link at the top.
But in specific I'm wondering how you would express this bit of Python code in Javascript. Basically _d2 is inside a class definition for Player.
def _d2(self, rating_list, RD_list):
tempSum = 0
for i in range(len(rating_list)):
tempE = self._E(rating_list[i], RD_list[i])
tempSum += math.pow(self._g(RD_list[1]), 2) * tempE * (1 - tempE)
return 1 / (math.pow(self._q, 2) * tempSum)
I've got the functions e and g defined like so, and q is a constant:
Player.prototype.e = function(this, ratingList, rdList) {
// Stuff goes here
}
In Javascript you don't need o pass the self explicitly (Python is the "weird" one here, actually)
Player.prototype.e = function(rating_list, RD_list){
//replace "self" with "this" here:
var tempSum = 0; //if you don't use the "var", tempSum will be a global
// instead of a local
for(var i=0; i<rating_list.length; i++){ //plain old for loop - no foreach in JS
var tempE = this._E( ... ); //note that in JS, just like in Python,
//variables like this have function scope and
//can be accessed outside the loop as well
tempSum += Math.pow( ... ) //the Math namespace is always available
//Javascript doesn't have a native module system
}
return (...);
}
This should work all right.
The only tricky thing you need to know about this is that it is very promiscuous. This means that is is determined by how you call the function:
obj.e(); //if you do a method-like call, the this will be set to obj
However, there is no magic binding behind the scenes. The following works in python but does not work in Javascript:
f = obj.e
f(); //looks like a normal function call. This doesn't point to obj

Categories

Resources