Non-decimal radices/Convert: Difference between revisions

(→‎{{header|Haskell}}: + Devanagari and HinduArabic digits)
Line 1,454:
 
=={{header|JavaScript}}==
===ES5===
<lang javascript>k = 26
s = k.toString(16) //gives 1a
Line 1,514 ⟶ 1,515:
}
</lang>
 
===ES6===
 
For more flexibility with digit variants (upper and lower case hex, digits in other languages/scripts etc) we can define '''toBase'''(intBase, n) in terms of a more general '''inBaseDigits'''(strDigits, n) which derives the base from the number of digits to be used.
 
<lang JavaScript>(() => {
'use strict';
 
// toBase :: Int -> Int -> String
const toBase = (intBase, n) =>
intBase < 36 && intBase > 0 ?
inBaseDigits('0123456789abcdef'.substr(0, intBase), n) : [];
 
 
// inBaseDigits :: String -> Int -> [String]
const inBaseDigits = (digits, n) => {
const intBase = digits.length;
 
return unfoldr(maybeResidue => {
const [divided, remainder] = quotRem(maybeResidue.new, intBase);
 
return {
valid: divided > 0,
value: digits[remainder],
new: divided
};
}, n)
.join('');
};
 
 
// GENERIC FUNCTIONS
 
// unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
const unfoldr = (mf, v) => {
var xs = [];
return [until(
m => !m.valid,
m => {
const m2 = mf(m);
return (
m2.valid && (xs = [m2.value].concat(xs)),
m2
);
}, {
valid: true,
value: v,
new: v,
}
)
.value
].concat(xs);
};
 
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
 
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
const go = x => p(x) ? x : go(f(x));
return go(x);
}
 
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = (m, n) => [Math.floor(m / n), m % n];
 
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
 
 
// OTHER FUNCTIONS DERIVABLE FROM inBaseDigits
 
// inLowerHex :: Int -> String
const inLowerHex = curry(inBaseDigits)('0123456789abcdef');
 
/// inUpperHex :: Int -> String
const inUpperHex = curry(inBaseDigits)('0123456789ABCDEF');
 
// inOctal :: Int -> String
const inOctal = curry(inBaseDigits)('01234567');
 
// inDevanagariDecimal :: Int -> String
const inDevanagariDecimal = curry(inBaseDigits)('०१२३४५६७८९');
 
 
// TESTS
// testNumber :: [Int]
const testNumbers = [255, 31, 97];
 
return testNumbers.map(n => show({
binary: toBase(2, n),
base5: toBase(5, n),
hex: toBase(16, n),
upperHex: inUpperHex(n),
octal: inOctal(n),
devanagariDecimal: inDevanagariDecimal(n)
}));
})();</lang>
 
{{Out}}
<pre>{
"binary": "11111111",
"base5": "2010",
"hex": "ff",
"upperHex": "FF",
"octal": "377",
"devanagariDecimal": "२५५"
}, {
"binary": "11111",
"base5": "111",
"hex": "1f",
"upperHex": "1F",
"octal": "37",
"devanagariDecimal": "३१"
}, {
"binary": "1100001",
"base5": "342",
"hex": "61",
"upperHex": "61",
"octal": "141",
"devanagariDecimal": "९७"
}</pre>
 
=={{header|jq}}==
9,655

edits