1/**
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16/**
17 * @file: Tools
18 */
19
20
21/**
22 * Carry when the time is greater than 9 seconds
23 */
24const NINE_MAX = 9;
25
26/**
27 * Divide by 60 to get minutes and seconds
28 */
29const SIXTY_SECONDS = 60;
30const SEC_VAL = 1000;
31const MIN_VAL = SIXTY_SECONDS * SEC_VAL
32
33export default class Utils {
34  private static sUtils: Utils
35
36  public static getInstance(): Utils {
37    if (Utils.sUtils == null) {
38      Utils.sUtils = new Utils()
39    }
40    return Utils.sUtils;
41  }
42
43  /**
44   * format phone number
45   *
46   * @param { string } phoneNumber
47   */
48  public formatPhoneNum(phoneNumber) {
49    if (/^1\d{10}$/.test(phoneNumber)) {
50      const str01 = phoneNumber.substring(0, 3);
51      const str02 = phoneNumber.substring(3, 7);
52      const str03 = phoneNumber.substring(7, 11);
53      return `${str01} ${str02} ${str03}`;
54    }
55    return phoneNumber;
56  }
57
58  /**
59   * format time
60   *
61   * @param { number } count
62   */
63  public formatTime(count) {
64    const second = Math.floor((count % MIN_VAL) / SEC_VAL);
65    const minute = Math.floor((count / MIN_VAL) % SIXTY_SECONDS);
66    const hour = Math.floor(count / (SIXTY_SECONDS * MIN_VAL));
67    const secondStr = second <= NINE_MAX ? '0' + second : second;
68    const minuteStr = minute <= NINE_MAX ? '0' + minute : minute;
69    return hour > 0 ? `${hour}:${minuteStr}:${secondStr}` : `${minuteStr}:${secondStr}`;
70  }
71
72  /**
73   * debounce
74   *
75   * @param {Function} func
76   *
77   * @param {Number} delay
78   *
79   * @return function
80   */
81  public debounce(func, delay = 200) {
82    let timer = null;
83    return function () {
84      clearTimeout(timer);
85      timer = setTimeout(() => {
86        func.apply(this, arguments);
87      }, delay);
88    };
89  }
90}