-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.js
79 lines (67 loc) · 1.79 KB
/
helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//fungsi untuk perhitungan sum.dlll
function sum (x) {
return x.reduce((a, b) => a + b)
}
function product (x, y) {
return x.map((value, index) => (x[index] * y[index]))
}
function dotProduct (x, y) {
return sum(product(x, y))
}
function mean (x) {
return sum(x) / x.length
}
function residuals (x) {
let average = mean(x)
return x.map(el => el - average)
}
function variation (x) {
let average = mean(x)
let squaredResiduals = x.map(el => Math.pow(el - average, 2))
return sum(squaredResiduals) / (x.length)
}
function sd (x) {
return Math.pow(variation(x), 0.5)
}
function flattenDeep (arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), [])
}
function intersection (array1, array2) {
return array1.filter(value => array2.indexOf(value) !== -1)
}
function arrayToRanks (x) {
let sortedArray = [...x].sort((a, b) => a - b)
// Initial ranks
let ranksArray = x.map(el => sortedArray.indexOf(el) + 1)
// Fix tied ranks
let tied = {}
for (let r of [...new Set(ranksArray)]) {
let len = ranksArray.filter(el => el === r).length
tied[r] = len === 1 ? r : sum([...Array(len).keys()].map(el => el + r)) / len
}
ranksArray = ranksArray.map(el => tied[el])
return ranksArray
}
function pearson (x, y) {
return dotProduct(residuals(x), residuals(y)) / (sd(x) * sd(y) * x.length)
}
function spearman (x, y) {
let rankedX = arrayToRanks(x)
let rankedY = arrayToRanks(y)
let squaredRankDifferece = rankedX.map((value, index) => Math.pow(rankedX[index] - rankedY[index], 2))
return 1 - 6 * (sum(squaredRankDifferece) / (Math.pow(x.length, 3) - x.length))
}
module.exports = {
sum,
product,
dotProduct,
mean,
residuals,
variation,
sd,
flattenDeep,
intersection,
arrayToRanks,
pearson,
spearman
}