-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (61 loc) · 1.51 KB
/
Copy pathindex.js
File metadata and controls
69 lines (61 loc) · 1.51 KB
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
function isPrime(num) {
if (typeof num !== "number") throw TypeError('This is not a valid number');
for (var i = 2; i <= Math.sqrt(num); i++)
if (num % i === 0) return false;
return num > 1;
}
function countPrime(num) {
if (typeof num !== "number") throw TypeError('This is not a valid number');
let count = 0;
for (let i = 2; i < num; i++) {
if (isPrime(i)) count++
}
return count
}
function fraction(num) {
if (typeof num !== "number") throw TypeError('This is not a valid number');
if (num <= 1) return 1;
return num * fraction(num - 1)
}
function permutaion(nums, sets = [], results = []) {
if (!nums.length) results.push([...sets]);
for (let i = 0; i < nums.length; i++) {
const newNums = nums.filter((item, index) => index !== i)
sets.push(nums[i])
permutaion(newNums, sets, results)
sets.pop()
}
return results
}
function combination(m, n) {
if (typeof m !== "number" || typeof n !== "number" || m < n) throw TypeError('This is not a valid number');
return fraction(m) / fraction(n) / fraction(m - n)
}
function countElement(arr) {
const result = arr.reduce((obj, item) => {
if (item in obj) {
obj[item]++
} else {
obj[item] = 1
}
return obj
}, {})
return result
}
function objectSort(obj) {
const sorted = Object.keys(obj)
.sort()
.reduce((acc, key) => ({
...acc, [key]: obj[key]
}), {})
return sorted
}
module.exports = {
isPrime,
countPrime,
countElement,
combination,
permutaion,
objectSort,
fraction
}