Skip to content

Instantly share code, notes, and snippets.

@AnastasiaDunbar
Last active October 11, 2018 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnastasiaDunbar/6c3c7b6ccf767797548f8bc193326ccc to your computer and use it in GitHub Desktop.
Save AnastasiaDunbar/6c3c7b6ccf767797548f8bc193326ccc to your computer and use it in GitHub Desktop.
const LOWPASS=0,HIGHPASS=1,BANDPASS=2;
class Filter{
constructor(mode){
this.cutoff=.99;
this.resonance=0;
this.mode=mode;
this.b0=0;this.b1=0;this.b2=0;this.b3=0;
this.feedbackAmount=0;
this.cutoffMod=0;
}
process(input){
if(input===0){return 0;}
var calculatedCutoff=this.getCalculatedCutoff();
this.b0+=calculatedCutoff*(input-this.b0+this.feedbackAmount*(this.b0-this.b1));
this.b1+=calculatedCutoff*(this.b0-this.b1);
this.b2+=calculatedCutoff*(this.b1-this.b2);
this.b3+=calculatedCutoff*(this.b2-this.b3);
switch(this.mode){
case LOWPASS:return this.b3;
case HIGHPASS:return input-this.b3;
case BANDPASS:return this.b0-this.b3;
}
return 0;
}
getCalculatedCutoff(){
return Math.max(Math.min(this.cutoff+this.cutoffMod,.99),.001);
}
calculateFeedbackAmount(){
this.feedbackAmount=this.resonance+this.resonance/(1-this.getCalculatedCutoff());
}
setCutoffMod(value){this.cutoffMod=value;this.calculateFeedbackAmount();}
setCutoff(value){this.cutoff=value;this.calculateFeedbackAmount();}
setResonance(value){this.resonance=value;this.calculateFeedbackAmount();}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment