(diff: number, localeFunc: LocaleFunc)
| 42 | * @returns |
| 43 | */ |
| 44 | export function formatDiff(diff: number, localeFunc: LocaleFunc): string { |
| 45 | /** |
| 46 | * if locale is not exist, use defaultLocale. |
| 47 | * if defaultLocale is not exist, use build-in `en`. |
| 48 | * be sure of no error when locale is not exist. |
| 49 | * |
| 50 | * If `time in`, then 1 |
| 51 | * If `time ago`, then 0 |
| 52 | */ |
| 53 | const agoIn = diff < 0 ? 1 : 0; |
| 54 | |
| 55 | /** |
| 56 | * Get absolute value of number (|diff| is non-negative) value of x |
| 57 | * |diff| = diff if diff is positive |
| 58 | * |diff| = -diff if diff is negative |
| 59 | * |0| = 0 |
| 60 | */ |
| 61 | diff = Math.abs(diff); |
| 62 | |
| 63 | /** |
| 64 | * Time in seconds |
| 65 | */ |
| 66 | const totalSec = diff; |
| 67 | |
| 68 | /** |
| 69 | * Unit of time |
| 70 | */ |
| 71 | let idx = 0; |
| 72 | |
| 73 | for (; diff >= SEC_ARRAY[idx] && idx < SEC_ARRAY.length; idx++) { |
| 74 | diff /= SEC_ARRAY[idx]; |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Math.floor() is alternative of ~~ |
| 79 | * |
| 80 | * The differences and bugs: |
| 81 | * Math.floor(3.7) -> 4 but ~~3.7 -> 3 |
| 82 | * Math.floor(1559125440000.6) -> 1559125440000 but ~~1559125440000.6 -> 52311552 |
| 83 | * |
| 84 | * More information about the performance of algebraic: |
| 85 | * https://www.youtube.com/watch?v=65-RbBwZQdU |
| 86 | */ |
| 87 | diff = Math.floor(diff); |
| 88 | |
| 89 | idx *= 2; |
| 90 | |
| 91 | if (diff > (idx === 0 ? 9 : 1)) idx += 1; |
| 92 | |
| 93 | return localeFunc(diff, idx, totalSec)[agoIn].replace('%s', diff.toString()); |
| 94 | } |
| 95 | |
| 96 | /** |
| 97 | * calculate the diff second between date to be formatted an now date. |
no outgoing calls
no test coverage detected
searching dependent graphs…