lodash#differenceBy JavaScript Examples

The following examples show how to use lodash#differenceBy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: workflows.js    From holo-schedule with MIT License 6 votes vote down vote up
syncOpenLives = async () => {
  const [currentLives, scheduledLives] = partition(filterLives(await getOpenLives({
    membersMask: getMembersMask(getSubscriptionByMember()),
    startBefore: getUnixAfterDays(7),
  })), ({ start_at: startAt }) => dayjs().isAfter(startAt))

  await browser.action.setBadgeText({ text: currentLives.length.toString() })

  console.log(`[background/workflow]Badge text has been set to ${currentLives.length}`)

  // Subscription is simplified cause here is the only mutation of currentLives
  const endedLives = getCachedEndedLives() ?? []
  // Skip if endedLives is empty
  if (endedLives.length > 0) {
    differenceBy((getCachedCurrentLives() ?? []), currentLives, 'id').map(live => ({
      ...live, duration: dayjs().diff(dayjs(live['start_at']), 'second'),
    })).forEach(live => {
      const index = findLastIndex(
        endedLives,
        ({ start_at: startAt }) => startAt <= live['start_at'],
      )
      endedLives.splice(index + 1, 0, live)
    })
  }

  await Promise.resolve({
    [CURRENT_LIVES]: currentLives,
    [SCHEDULED_LIVES]: scheduledLives,
    [ENDED_LIVES]: limitRight(filterLives(uniqRightBy(endedLives, 'id')), MAX_LIVES_LENGTH),
  }).then(data => store.set(data))
    .catch(data => store.set(data, { local: false }))

  return [...currentLives, ...scheduledLives]
}
Example #2
Source File: index.js    From holo-schedule with MIT License 5 votes vote down vote up
initOnce = async () => {
  global.workflows = workflows
  global.store = store
  global.alarm = alarm

  await store.init()
  await alarm.init(store)
  await i18n.init(store)
  await workflows.init()

  if (isStartUp) {
    // Use new state
    await clearCachedEndedLives()
    await setIsPopupFirstRun(true)
    console.log('[background]States have been cleared.')
  }

  requests.onSuccessRequest.addEventListener(() => {
    const lastSuccessRequestTime = getLastSuccessRequestTime() ?? getUnix()
    const timestamp = getUnix()
    if (timestamp - lastSuccessRequestTime > 60 * 5) {
      clearCachedEndedLives()
    }
    setLastSuccessRequestTime(timestamp)
  })

  store.subscribe(ENDED_LIVES, async (lives, prevLives) => workflows.syncHotnesses(
    reject(differenceBy(lives, prevLives, 'id'), 'hotnesses'),
  ))

  browser.alarms.onAlarm.addListener(handleAlarm)
  browser.alarms.create(ALARM_NAME, { periodInMinutes: 1 })

  browser.runtime.sendMessage('background alive').catch(err => {
    if (err.message.startsWith('Could not establish connection.')) {
      console.log('[background]on message error. Keep calm, this error is in expect.')
    } else {
      console.log('[background]on message error', err.message)
    }
  })
}
Example #3
Source File: index.js    From holo-schedule with MIT License 4 votes vote down vote up
alarm = {
  $defaultIsNtfEnabled: true,
  $store: undefined,
  livesToAlarm: undefined,
  firedAlarms: undefined,
  savedCurrentLives: [],
  savedScheduledLives: [],
  schedule(live) {
    this.livesToAlarm.add(live)
    return this.$store.set({ [LIVES_TO_ALARM]: JSON.parse(JSON.stringify(this.livesToAlarm)) })
  },
  remove(live) {
    this.livesToAlarm.remove(find(this.livesToAlarm, { id: live['id'] }))
    return this.$store.set({ [LIVES_TO_ALARM]: JSON.parse(JSON.stringify(this.livesToAlarm)) })
  },
  isScheduled(live) {
    return find(this.livesToAlarm, { id: live['id'] })
  },
  getIsNtfEnabled() {
    return this.$store.get(IS_NTF_ENABLED) ?? this.$defaultIsNtfEnabled
  },
  fire(live, isGuerrilla = false) {
    const { id, title } = live

    this.remove({ id })

    if ((find(this.firedAlarms, { id }) && isGuerrilla) || !this.getIsNtfEnabled()) return

    const member = workflows.getMember(live)

    this.firedAlarms.add({ id })
    this.$store.set({ [FIRED_ALARMS]: JSON.parse(JSON.stringify(this.firedAlarms)) })

    notification.create(id.toString(), {
      title,
      message: i18n.getMessage(
        `notification.${isGuerrilla ? 'guerrilla' : 'reminder'}`, { name: member['name'] },
      ),
      iconUrl: member['avatar'] ?? browser.runtime.getURL('assets/default_avatar.png'),
      onClick() {
        browser.tabs.create({ url: constructUrl(live) }).then(
          () => console.log('[background/alarm]Successfully created a tab'),
        )
      },
    })
  },
  async init(store) {
    this.$store = store
    this.livesToAlarm = createEnhancedArray(this.$store.get(LIVES_TO_ALARM), 50)
    this.firedAlarms = createEnhancedArray(this.$store.get(FIRED_ALARMS), 30)

    await store.set({ [IS_NTF_ENABLED]: this.getIsNtfEnabled() })

    store.subscribe(CURRENT_LIVES, (lives, prevLives) => {
      // Skip the first run
      if (prevLives === undefined) {
        return
      }

      differenceBy(lives, prevLives, 'id').forEach(live => {
        // Scheduled alarms
        if (this.isScheduled(live)) {
          this.fire(live)
        }
        // Guerrilla lives
        if (isGuerrillaLive(live)) {
          this.fire(live, true)
        }
      })
    })

    store.subscribe(SCHEDULED_LIVES, (lives, prevLives) => {
      // Skip the first run
      if (prevLives === undefined) {
        return
      }

      // Guerrilla lives
      differenceBy(lives, prevLives, 'id').forEach(live => {
        if (isGuerrillaLive(live)) {
          this.fire(live, true)
        }
      })
    })
  },
}