153 142 139 bytes
Accepts input as a string. Undefined behavior for invalid input, though it should terminate without error on any string I can think of. Not necessarily before the heat-death of the universe though, particularly for long strings.
Saved 11 bytes by refactoring the
reduce() calls into
map() calls, and by implicitly copying the array
a in the function parameter, instead of in within the context of the
Saved 3 bytes thanks to @Neil's suggestion to convert
input => (
(char, decimal, [...charArray]) =>
[...'' + 1e9].map(
(unused, digit) => sum +=
digit + decimal && digit != char ?
charArray.splice(decimal, 1, digit)
, sum = 0
, prime = test => eval('for(factor = test; test % --factor;); factor == 1')
The function uses a two-level
map() to sum the amount of permutations that pass the primality test, which was borrowed and modified from this answer.
reduce((accumulator, currentValue, currentIndex, array) => aggregate, initialValue)
So for example, to calculate the sum of an array, you would pass an
0, and return an
aggregate equal to
accumulator + currentValue. Modifying this approach slightly, we instead calculate the number of permutations that pass the primality test:
(passedSoFar, currentDecimal, currentIndex, digitArray) =>
passedSoFar + prime(getPermutation()) :
That is essentially the inner
reduce(), which iterates all the permutations of the
digitArray by changing each
decimal to a specific
permutatedDigit. We then need an outer
reduce() to iterate all possible
permutatedDigit's with which to replace each
decimal, which is just
Abnormalities in implementation
[...''+1e9].map((u,j)=>... was the shortest way @Neil could think of to iterate an argument
9. It would be preferable to do so with
u is not useful for each element in the array, in this case.
i+j in the ternary condition checks to ensure that
0 is not a possible permutation of the leading digit, as per the challenge specification.
j!=c ensures that the original
n is not a candidate to go through the primality test.
(a.splice(i,1,j),a.join``) is kind of a mess.
splice() replaces the digit at
decimal == i with the
permutatedDigit == j, but since
splice() returns the removed elements (in this case, would be equal to
[a[i]]) instead of the modified array, we must use the comma operator to pass the modified array
a to the primality test, but not before
join()ing it into a number string.
eval() is to save a byte since, compared to the more canonical approach, it is shorter:
The reference to the prime test
p is initialized in an unused argument to the