Hi!
I am working through the excellent Site Point book, JavaScript, Novice to Ninja.
Chapter 11, Functional Programming
I have been trying to tease out how exactly the syntax works…and I have created this little file:
// const square = (x) => x * x
// const mean = (array) => sum(array) / array.length
// const variance = (array) => sum(array, square) / array.length - square(mean(array))
// const hypoteneuse = (a, b) => Math.sqrt(square(a) + square(b))
// const areaC = (d) => (3.14 + square(d))
// const stdDev = (array) => Math.sqrt(sum(square(array - array)) / (array.length - 1))
function sum (array, callback) {
if (callback) {
array = array.map(callback)
}
return array.reduce((a, b) => a + b)
}
console.log(sum([4, 8, 9, 7, 6, 9]))
When I try to use the function for standard deviation (const stdDev) by uncommenting the appropriate functions and doing
console.log(stdDev[4, 8, 9, 7, 6, 9])) - I get
“array.reduce is not a function” as an error message
That wouldn’t make a difference… the .reduce() method is even supported by IE9+. Rather, that error message means that you’re passing something other than an array to the sum() function. Now in this line
you are subtracting array from array, but subtraction only works for numbers; so the result you are passing to square() is NaN (and NaN * NaN is still NaN).
Thank you!!
I had deduced that it had to be something in the stdDev function that I had tried writing on my own…
And I had had the thought that it probably was something to do with array - array…
Dang!!!
Happy!!!
Thank you!!!
Just thank you. I think I have taught myself quite a lot quite quickly and it’s just going to take some (a lot) of practice before I can easily remember enough —
Anyway, thank you again!
const square = (x) => x * x
// const mean = (array) => sum(array) / array.length
// const variance = (array) => sum(array, square) / array.length - square(mean(array))
// const hypoteneuse = (a, b) => Math.sqrt(square(a) + square(b))
// const areaC = (d) => (3.14 + square(d))
const stdDev = (array) => Math.sqrt(sum(square((sum(array)) - (sum(array)))) / (array.length - 1))
function sum (array, callback) {
if (callback) {
array = array.map(callback)
}
return array.reduce((a, b) => a + b)
}
console.log(stdDev([4, 8, 9, 7, 6, 9]))
// console.log(typeof )
Is it okay to ask…
Why does this not “work”
The attempt is to use sum() to sum the arrays then subtract them…
I can see that things are getting pretty convoluted in my code
But still…can’t follow why it wouldn’t “work”
The plot thickens…
const subSum = (array) => (sum(array)) - (sum(array))
This does "work" as intended...changing the array into a number ... which makes sense -- also completely losing track of the idea of standard deviation...but I am really just practicing ...
Anyway...thanks in advance