简体   繁体   中英

Javascript Algorithm Attempting to Implement Call Back Function

Question

A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

For example, take 153 (3 digits):

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

and 1634 (4 digits):

1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

The Challenge:

Your code must return true or false depending upon whether the given number is a Narcissistic number in base 10.

Error checking for text strings or other invalid inputs is not required, only valid integers will be passed into the function.

My Code

 function narcissistic(value) { let valString = value.toString().split(''); let integerSet = valString.map((item)=>{ return Number(item); }) let keyFunc = function powerCalc(test){ let a = test[test.length-1]; return test.map((item)=>{ return Math.pow(item, a); }).reduce((total, item)=>{ return total + item; }, 0); } console.log(keyFunc(153)); if(keyFunc(integerSet)==value){ return true; } else { return false; } } console.log(narcissistic(12432)); console.log(narcissistic(153));

The Problem

My console is saying that test.map is not a function.

How can I adjust that function to make it work?

Two small mistakes:

 function narcissistic(value) { let valString = value.toString().split(''); let integerSet = valString.map((item)=>{ return Number(item); }) let keyFunc = function powerCalc(test){ let a = test.length; // <------- "raised to the power of the number of digits" return test.map((item)=>{ return Math.pow(item, a); }).reduce((total, item)=>{ return total + item; }, 0); } // console.log(keyFunc(153)); // <-- This was throwing an error if(keyFunc(integerSet)==value){ return true; } else { return false; } } console.log(narcissistic(12432));// false console.log(narcissistic(153)); // true console.log(narcissistic(371)); // true console.log(narcissistic(7)); // true

And with a bit of rewriting:

 function narcissistic(value) { const integerSet = value.toString().split('').map(Number); const pow = integerSet.length; const sum = integerSet.reduce((total, item) => total + Math.pow(item, pow), 0); return sum == value; } console.log(narcissistic(12432));// false console.log(narcissistic(153)); // true console.log(narcissistic(371)); // true console.log(narcissistic(7)); // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM