From 5448a9645e95cfbbd106de4755f6c97bc1cc4803 Mon Sep 17 00:00:00 2001 From: Suvash Thapaliya Date: Tue, 2 Mar 2021 00:44:39 +0100 Subject: [PATCH] Add functions to layouts module for a cleaner API --- src/layouts/index.js | 25 ++++++++++++++++++++++++- test/layouts.spec.js | 35 +++++++++++++++++++++++++++++++---- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/src/layouts/index.js b/src/layouts/index.js index 784148f..d409a92 100644 --- a/src/layouts/index.js +++ b/src/layouts/index.js @@ -1,9 +1,32 @@ import romanized from "./romanized"; import traditional from "./traditional"; -const layouts = { +const layoutStore = { romanized: romanized, traditional: traditional, }; +function availableLayouts() { + return Object.keys(layoutStore); +} + +function isValidLayout(layout) { + return availableLayouts().includes(layout); +} + +function fetchLayout(layout) { + if (isValidLayout(layout)) { + return layoutStore[layout]; + } else { + const msg = "Invalid Layout : " + layout; + throw new Error(msg); + } +} + +const layouts = { + fetchLayout: fetchLayout, + isValidLayout: isValidLayout, + availableLayouts: availableLayouts, +}; + export default layouts; diff --git a/test/layouts.spec.js b/test/layouts.spec.js index 989d2be..d41ab8c 100644 --- a/test/layouts.spec.js +++ b/test/layouts.spec.js @@ -2,9 +2,36 @@ import { expect } from "chai"; import layouts from "../src/layouts"; describe("layouts", () => { - it("should return an object of available layouts", () => { - expect(layouts).to.be.an("object"); - expect(layouts).to.have.property("romanized"); - expect(layouts).to.have.property("traditional"); + describe("availableLayouts()", () => { + it("should return a list of available layouts", () => { + const expected = ["romanized", "traditional"]; + expect(layouts.availableLayouts()).to.deep.equal(expected); + }); + }); + + describe("isValidLayout(layout_name)", () => { + it("should return a boolean given a layout name", () => { + expect(layouts.isValidLayout("bogus")).to.equal(false); + expect(layouts.isValidLayout("random")).to.equal(false); + + expect(layouts.isValidLayout("romanized")).to.equal(true); + expect(layouts.isValidLayout("traditional")).to.equal(true); + }); + }); + + describe("fetchLayout(layout_name)", () => { + it("when valid should return a layout object", () => { + expect(layouts.fetchLayout("romanized")).to.be.an("object"); + expect(() => { + layouts.fetchLayout("romanized"); + }).to.not.throw("Invalid Layout"); + expect(layouts.fetchLayout("traditional").name).to.equal("traditional"); + }); + + it("when invalid should throw an exception", () => { + expect(() => { + layouts.fetchLayout("bogus"); + }).to.throw("Invalid Layout"); + }); }); });