Array.reduce() takes an array and combines elements from the array with an accumulator until all the elements are consumed.
Is there a function (often called "unfold" in other languages) that starts with a value and keeps generating elements until a complete array is produced (the accumulator is depleted)?
I am trying to do this as part of converting between arbitrary bases. The code as I have it is as follows, but I would like to eliminate the raw loop.
var dstAlphabet = "0123456789ABCDEFGH";
var dstBase = dstAlphabet.length;
var wet = BigInteger(100308923948716816384684613592839);
var digits_reversed = [];
while (wet.isPositive())
{
// var digitVal = wet % dstBase
var divRem = wet.divRem(dstBase); // [result of division, remainder]
wet = divRem[0];
digits_reversed.push(dstAlphabet.charAt(divRem[1].toJSValue()));
}
return digits_reversed.reverse().join("");
// These days you can do it in one line:
const unfold = (accumulator, length) => length <= 0 ? accumulator : unfold([length, ...accumulator], length -1)
// invoke it like this:
const results = unfold([], 5)
// expected results: 1,2,3,4,5
console.log(results.join(','))
Since we're looking for a concise way to generate a given number of elements as an array, this "unfold" function does it with recursion.
The first argument is the accumulator array. This needs to be passed along, and eventually is returned when it holds the entire collection. The second argument is the limiter. This is what you use to dimension your resulting array.
In each call, we first test if the base case is reached. If so, the answer is easy: just return the given array. For the general case, we are again unfolding, but with a smaller value, so we prepend one value to accumulator, and decrement length.
Since we're using the spread operator and a 'computed-if' the function is concise. Using the arrow style also lets us avoid the 'function' and 'return' keywords, as well as curly-braces. So the whole thing is a one-liner.
I basically use this technique as a for-loop substitute for React JSX, where everything needs to be an expression (Array.map()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With