Skip to content

Commit

Permalink
apps/docs: math/decibels
Browse files Browse the repository at this point in the history
  • Loading branch information
satelllte committed Oct 5, 2023
1 parent 5674e68 commit 43fcc06
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
23 changes: 23 additions & 0 deletions apps/docs/src/utils/math/decibels.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {describe, expect, it} from 'vitest';
import {gainToDecibels, dbMin} from './decibels';

describe('gainToDecibels', () => {
it('should convert gain to decibels correctly', () => {
expect(gainToDecibels(10)).toBeCloseTo(20.0);
expect(gainToDecibels(2)).toBeCloseTo(6.02);
expect(gainToDecibels(1)).toBeCloseTo(0);
expect(gainToDecibels(0.5)).toBeCloseTo(-6.02);
expect(gainToDecibels(0.25)).toBeCloseTo(-12.04);
expect(gainToDecibels(0.125)).toBeCloseTo(-18.06);
expect(gainToDecibels(0.01)).toBeCloseTo(-40);
expect(gainToDecibels(0.001)).toBeCloseTo(-60);
});

it(`should return ${dbMin} for extremely low values`, () => {
expect(gainToDecibels(1e-10)).toBeCloseTo(dbMin);
expect(gainToDecibels(1e-20)).toBeCloseTo(dbMin);
expect(gainToDecibels(1e-30)).toBeCloseTo(dbMin);
expect(gainToDecibels(1e-40)).toBeCloseTo(dbMin);
expect(gainToDecibels(0)).toBeCloseTo(dbMin);
});
});
8 changes: 8 additions & 0 deletions apps/docs/src/utils/math/decibels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const dbMin = -96;

export const gainToDecibels = (gain: number): number => {
let res = 20 * Math.log10(gain);
res = Number.isFinite(res) ? res : dbMin;
res = Math.max(res, dbMin);
return res;
};

0 comments on commit 43fcc06

Please sign in to comment.