From 0fa55416f9510b6c1a27b891ac3e8f7e2cded962 Mon Sep 17 00:00:00 2001 From: Syed Zawwar Ahmed <64926760+SyedZawwarAhmed@users.noreply.github.com> Date: Sun, 10 Oct 2021 19:57:22 +0500 Subject: [PATCH] Adding freecodecamp's Binary Agents Algorithm --- Algorithms/Javascript/binary-agents.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Algorithms/Javascript/binary-agents.js diff --git a/Algorithms/Javascript/binary-agents.js b/Algorithms/Javascript/binary-agents.js new file mode 100644 index 00000000..67cecd35 --- /dev/null +++ b/Algorithms/Javascript/binary-agents.js @@ -0,0 +1,24 @@ +// Takes a space separated binary string +// Return an English translated sentence of the passed binary string + +function binaryAgent(str) { + let convertedString = "" + let binaryArray = str.split(" ") + for (let i = 0; i < binaryArray.length; i++) { + let asciiCode = 0 + let positionFromLeft = 0 + for (let j = binaryArray[i].length - 1; j >= 0; j--) { + if (binaryArray[i][j] === "1") { + asciiCode += 2 ** positionFromLeft + } + positionFromLeft++; + } + convertedString += String.fromCharCode(asciiCode) + } + return convertedString + } + + // Sample + // const result = binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"); + + // console.log(result) \ No newline at end of file