-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathnumerical-palindrome-number-3-dot-5.js
64 lines (55 loc) · 1.8 KB
/
numerical-palindrome-number-3-dot-5.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
const errorMessages = {
notValid: 'Not valid',
notFound:'No palindromes found',
};
function createMemoizedIsSubPalindrome() {
const cache = {};
return (number) => {
if (number in cache) return cache[number];
const strNum = number.toString();
const result = strNum.split('').reverse().join('') == strNum;
cache[number] = result;
return result;
};
}
const isSubPalindrome = createMemoizedIsSubPalindrome();
function createMemoizedPalindrome() {
const cache = {};
return (num, palindromes = []) => {
let result;
if (num in cache) return cache[num];
if (typeof num !== 'number') {
result = errorMessages.notValid;
} else if (num < 0) {
result = errorMessages.notValid;
} else if (num < 10) {
result = errorMessages.notFound;
}
if (result) {
cache[num] = result;
return result;
}
if (isSubPalindrome(num)) {
palindromes.push(num);
}
palindrome(+num.toString().slice(1), palindromes);
palindrome(+num.toString().slice(0, -1), palindromes);
if (!palindromes.length) {
cache[num] = errorMessages.notFound;
return errorMessages.notFound;
}
return [...new Set(palindromes.sort((a, b) => a - b))];
};
}
const palindrome = createMemoizedPalindrome();
// console.log(palindrome('ACCDDCCA'),errorMessages.notValid);
// console.log(palindrome('1551'),errorMessages.notValid);
// console.log(palindrome(-4505),errorMessages.notValid);
// console.log(palindrome(2),errorMessages.notFound);
// console.log(palindrome(1551),[55,1551]);
const start = Date.now();
console.log(palindrome(221122),[11,22,2112,221122]);
const end = Date.now();
console.log((end - start) / 1000, 'Seconds.');
// console.log(palindrome(10015885),[88,1001,5885]);
// console.log(palindrome(13598),errorMessages.notFound);