Given Integer, Return Boolean
JavaScript
const narcissistic = n => {
let a = String(n).split('')
return a
.map(x => Number(x))
.map(x => x**a.length)
.reduce((x,y) => x+y) === n
}console.log(narcissistic(7), true)
console.log(narcissistic(371), true)
console.log(narcissistic(122), false)
console.log(narcissistic(4887), false)
The JavaScript code above can be copy/pasted into Chrome DevTools console or Node.js REPL.
The const
keyword is used to declare a variable with an immutable binding. The optional name narcissistic
describes a number which matches specs implied by the methods used.
- an integer is given, and named
n
- a variable is declared, and named
a
;n
is converted to a string so that it cansplit()
into an array of one or more integers. return
statement maps integer strings to integer numbers; maps integer numbers to integer to the power value based on the length of the array. For example, if the given integer has 3 digits, then each digit will be multiplied to the 3rd power, e.g.x**a.length
or x³; reduce() method gives sum of all multiplied values in the array. That sum is compared with the original given integer for equality.
Explanations for Python and Ruby versions may be added later.