Back to home

Writing testsAnagramsTesting
Anagrams in JavaScript main image

Anagrams in JavaScript

This blog assumes a global install of mocha, although that can also be installed locally. chai is also required as the assertion library - install as a dev dependency.

Writing tests

In anagrams.mocha.js:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 const lib = require("./strcmpSolution"); // const mocha = require('mocha'); const chai = require("chai"); const { expect } = chai; describe("check lowercase of two strings are anagrams", function () { it("should handle basic anagram", function () { const res = lib.anagram("race car", "racrace"); expect(res).to.equal(true); }); it("should handle punctuation", function () { const res = lib.anagram("race car", "RACE! CAR!"); expect(res).to.equal(true); }); it("should handle non-anagrams with different lengths", function () { const res = lib.anagram("test", "testa"); expect(res).to.equal(false); }); it("should handle non-anagrams with same length", function () { const res = lib.anagram("tests", "testa"); expect(res).to.equal(false); }); it("should handle anagrams with varying char length", function () { const res = lib.anagram("rrracb", "abcrrrr"); expect(res).to.equal(false); }); });

Anagrams

In index.js.

1 2 3 4 5 6 7 8 const anagram = (strA, strB) => cleanStr(strA) === cleanStr(strB); const cleanStr = (str) => str.replace(/[^\w]/g, "").toLowerCase().split("").sort().join(""); module.exports = { anagram, };

Testing

Change into directory and run mocha anagrams.mocha.js.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.