CRC-32: Difference between revisions

Content added Content deleted
Line 984: Line 984:
'use strict';
'use strict';


// --------------------- CRC-32 ----------------------
const main = () =>
showHex(
crc32('The quick brown fox jumps over the lazy dog')
);


// crc32 :: String -> Int
// crc32 :: String -> Int
const crc32 = str => {
const crc32 = str => {

// table :: [Int]
// table :: [Int]
const table = map(
const table = enumFromTo(0)(255).map(
n => take(9,
n => take(9)(
iterate(
iterate(
x => (
x => (
x & 1 ? z => 0xEDB88320 ^ z : id
x & 1 ? (
)(x >>> 1),
z => 0xEDB88320 ^ z
n
) : identity
)
)(x >>> 1)
)[8],
)(n)
enumFromTo(0, 255)
)[8]
);
return (
foldl(
(a, c) => (a >>> 8) ^ table[
(a ^ c.charCodeAt(0)) & 255
],
-1,
chars(str)
) ^ -1
);
);
return chars(str).reduce(
(a, c) => (a >>> 8) ^ table[
(a ^ c.charCodeAt(0)) & 255
],
-1
) ^ -1;
};
};


// GENERIC ABSTRACTIONS -------------------------------
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
showHex(
crc32('The quick brown fox jumps over the lazy dog')
);

// --------------------- GENERIC ---------------------


// chars :: String -> [Char]
// chars :: String -> [Char]
const chars = s => s.split('');
const chars = s =>
s.split('');



// enumFromTo :: Int -> Int -> [Int]
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
const enumFromTo = m =>
Array.from({
n => !isNaN(m) ? (
length: 1 + n - m
Array.from({
}, (_, i) => m + i);
length: 1 + n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);


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


// id :: a -> a
// identity :: a -> a
const id = x => x;
const identity = x =>
// The identity function.
x;



// iterate :: (a -> a) -> a -> Gen [a]
// iterate :: (a -> a) -> a -> Gen [a]
function* iterate(f, x) {
const iterate = f =>
let v = x;
// An infinite list of repeated
while (true) {
// applications of f to x.
yield(v);
function* (x) {
v = f(v);
let v = x;
}
while (true) {
yield(v);
}
v = f(v);
}
};


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


// showHex :: Int -> String
// showHex :: Int -> String
const showHex = n =>
const showHex = n =>
// Hexadecimal string for a given integer.
n.toString(16);
'0x' + n.toString(16);



// take :: Int -> [a] -> [a]
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
// take :: Int -> String -> String
const take = (n, xs) =>
const take = n =>
// The first n elements of a list,
xs.constructor.constructor.name !== 'GeneratorFunction' ? (
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
xs.slice(0, n)
) : [].concat.apply([], Array.from({
) : [].concat.apply([], Array.from({
Line 1,069: Line 1,080:
})();</lang>
})();</lang>
{{Out}}
{{Out}}
<pre>414fa339</pre>
<pre>0x414fa339</pre>


=={{header|Jsish}}==
=={{header|Jsish}}==