Binary digits: Difference between revisions

Content added Content deleted
No edit summary
m (→‎JS ES6: Tidied)
Line 2,767: Line 2,767:


===ES6===
===ES6===
The simplest showBin (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):
The simplest showBinary (or showIntAtBase), using default digit characters, would use JavaScript's standard String.toString(base):


<lang JavaScript>(() => {
<lang JavaScript>(() => {
"use strict";


// ------------------ BINARY DIGITS ------------------
// showIntAtBase_ :: // Int -> Int -> String
const showIntAtBase_ = (base, n) => (n)
.toString(base);


// showBin :: Int -> String
// showBinary :: Int -> String
const showBin = n => showIntAtBase_(2, n);
const showBinary = n =>
showIntAtBase_(2)(n);


// GENERIC FUNCTIONS FOR TEST ---------------------------------------------


// intercalate :: String -> [a] -> String
// showIntAtBase_ :: // Int -> Int -> String
const intercalate = (s, xs) => xs.join(s);
const showIntAtBase_ = base =>
n => n.toString(base);

// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);


// unlines :: [String] -> String
const unlines = xs => xs.join('\n');


// ---------------------- TEST -----------------------
// show :: a -> String
const show = x => JSON.stringify(x);
const main = () => [5, 50, 9000]
.map(n => `${n} -> ${showBinary(n)}`)
.join("\n");


// TEST -------------------------------------------------------------------


return unlines(map(
// MAIN ---
return main();
n => intercalate(' -> ', [show(n), showBin(n)]),
[5, 50, 9000]
));
})();</lang>
})();</lang>
{{Out}}
{{Out}}