Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

用 bitMap 对时间秒数去重

  • bitMap是什么

    • 通过一个bit位来表示某个元素对应的值或者状态
  • 方法

    • bitset 设置某个偏移位置的bit值为 1或0
    • bitcount 返回被设置为 1 的位的数量
  • 例子

    helper.postTweedleDuration = async function(userUuid, date, hourIndex, durations) {
        const key = `stats:tweelde_duration:${date}:${hourIndex}:${userUuid}`;
    
        const batch = client.batch();
        durations.forEach(duration => {
            const start = duration.start;
            const end = duration.end;
    
            const hourStart = start.clone().startOf('hours');
            const startIndex = start.diff(hourStart, 'seconds');
            const endIndex = end.diff(hourStart, 'seconds');
            const activeSecondOffsets  = range(startIndex, endIndex)
    
            activeSecondOffsets.forEach(offset => {
                batch.setbit(key, offset, '1');
            });
        });
        batch.expire(key, 60*60*24*2);
        return await batch.exec();
    }
    
    • 根据 日期、所在小时、用户uuid 创建一个键,记录该小时内,用户“每秒”的练琴情况
    • startIndex : 开始时间戳 离该小时0分的距离,比如1800
    • endIndex : 结束时间戳 离该小时0分的距离,比如1830
    • range方法 : 返回数组,包含这段距离之内的所有数字,[1800、1801...1829、1830]
      function range(start, end) {
          if (end <= start) return [];
          var foo = [];
          for (let i = start; i < end; i++) {
              foo.push(i);
          }
          return foo;
      }
      
    helper.getTweedleTotalDuration = async function(userUuid, date, hourIndex) {
        const key = `stats:tweelde_duration:${date}:${hourIndex}:${userUuid}`;
        return await RedisCore.bitcount(key);
    }
    
    • 返回该小时内,用户练琴的“总秒数”
    • 还需要 集合
      • 来记录有练琴的那些用户
      • 来记录有数据的那些小时
      • 便于最后知道要把什么同步到数据库