From 43fcc0679a7abb53e6a33270407e22b8ebcaf3c5 Mon Sep 17 00:00:00 2001 From: George Satellite Date: Thu, 5 Oct 2023 14:32:29 +0300 Subject: [PATCH] apps/docs: math/decibels --- apps/docs/src/utils/math/decibels.test.ts | 23 +++++++++++++++++++++++ apps/docs/src/utils/math/decibels.ts | 8 ++++++++ 2 files changed, 31 insertions(+) create mode 100644 apps/docs/src/utils/math/decibels.test.ts create mode 100644 apps/docs/src/utils/math/decibels.ts diff --git a/apps/docs/src/utils/math/decibels.test.ts b/apps/docs/src/utils/math/decibels.test.ts new file mode 100644 index 0000000..426cac9 --- /dev/null +++ b/apps/docs/src/utils/math/decibels.test.ts @@ -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); + }); +}); diff --git a/apps/docs/src/utils/math/decibels.ts b/apps/docs/src/utils/math/decibels.ts new file mode 100644 index 0000000..fb123b5 --- /dev/null +++ b/apps/docs/src/utils/math/decibels.ts @@ -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; +};