Skip to content

Commit

Permalink
feat(ljs:devices): add type narrowing helper isDeviceModelId
Browse files Browse the repository at this point in the history
  • Loading branch information
ofreyssinet-ledger committed Jun 5, 2024
1 parent 376cff7 commit 3b9c93c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/polite-ladybugs-prove.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ledgerhq/devices": patch
---

Add type narrowing helper isDeviceModelId
22 changes: 21 additions & 1 deletion libs/ledgerjs/packages/devices/src/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
import { DeviceModelId } from ".";
import { stringToDeviceModelId } from "./helpers";
import { stringToDeviceModelId, isDeviceModelId } from "./helpers";


const validDeviceModelsIds = ["nanoS", "nanoX", "blue", "nanoSP", "stax", "europa"];
const invalidDeviceModelsIds = ["does-not-exist", "", null, undefined];

describe("isDeviceModelId", () => {
validDeviceModelsIds.forEach(potentialModelId => {
test(`Input: ${potentialModelId} -> Expected output: true`, () => {
const result = isDeviceModelId(potentialModelId);
expect(result).toEqual(true);
});
});

invalidDeviceModelsIds.forEach(potentialModelId => {
test(`Input: ${potentialModelId} -> Expected output: false`, () => {
const result = isDeviceModelId(potentialModelId);
expect(result).toEqual(false);
});
});
});

type Test = {
input: [string, DeviceModelId];
Expand Down
12 changes: 7 additions & 5 deletions libs/ledgerjs/packages/devices/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { DeviceModelId } from ".";

export function isDeviceModelId(val: string | undefined | null): val is DeviceModelId {
if (!val) return false;
return Object.values(DeviceModelId).includes(val as DeviceModelId);
}

export const stringToDeviceModelId = (
strDeviceModelId: string,
defaultDeviceModelId: DeviceModelId,
): DeviceModelId => {
if (Object.values(DeviceModelId)?.includes(strDeviceModelId as DeviceModelId)) {
return DeviceModelId[strDeviceModelId as DeviceModelId];
}

return defaultDeviceModelId;
if (!isDeviceModelId(strDeviceModelId)) return defaultDeviceModelId;
return DeviceModelId[strDeviceModelId];
};

0 comments on commit 3b9c93c

Please sign in to comment.