{"size": 1749, "ext": "js", "max_stars_repo_path": "test/index.js", "max_stars_repo_name": "microlinkhq/async-memoize-one", "max_stars_repo_stars_event_min_datetime": "2020-12-03T04:23:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T06:02:04.000Z", "max_issues_repo_path": "test/index.js", "max_issues_repo_name": "microlinkhq/async-memoize-one", "max_issues_repo_issues_event_min_datetime": "2021-03-25T20:23:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T18:30:33.000Z", "max_forks_repo_path": "test/index.js", "max_forks_repo_name": "microlinkhq/async-memoize-one", "max_forks_repo_forks_event_min_datetime": "2021-04-01T03:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T13:08:28.000Z"}
{"max_stars_count": 12, "max_issues_count": 2, "max_forks_count": 2, "avg_line_length": 20.8214285714, "max_line_length": 85, "alphanum_fraction": 0.6460834763}
'use strict'

const pReflect = require('p-reflect')
const delay = require('delay')
const test = require('ava')

const memoizeOne = require('..')

test('memoize the last call', async t => {
  let i = 0

  const call = async (...args) =>
    args.reduce((total, current) => total + current) + i

  const memoizedCall = memoizeOne(call)
  const firstResponse = await memoizedCall(1, 2, 3)

  // Perform first call
  t.is(firstResponse, 6)

  // Increment i to equal 20
  i = 20

  // Perform second call, i should equal 0 as it remembers the previous.
  const secondResponse = await memoizedCall(1, 2, 3)

  t.is(secondResponse, 6)
})

test('does not use cache on new params', async t => {
  let i = 0

  const call = async (...args) =>
    args.reduce((total, current) => total + current) + i

  const memoizedCall = memoizeOne(call)
  const firstResponse = await memoizedCall(1, 2, 3)

  // Perform first call
  t.is(firstResponse, 6)

  // Increment i to equal 20
  i = 20

  // Perform second call, because the params are different it should do a fresh call.
  const secondResponse = await memoizedCall(1, 2, 4)

  t.is(secondResponse, 27)
})

test('prevent race condition', async t => {
  let i = 0

  const call = async () => {
    const value = ++i
    return value
  }

  const memoizedCall = memoizeOne(call)

  await Promise.all([memoizedCall(), memoizedCall(), memoizedCall()])

  t.is(i, 1)
})

test('`{ cachePromiseRejection: true }`', async t => {
  let i = 0

  const call = async () => {
    const value = ++i
    if (value === 1) throw new Error('oh no')
    return value
  }

  const memoizedCall = memoizeOne(call)

  pReflect(memoizedCall())
  await delay(100)
  pReflect(memoizedCall())
  pReflect(memoizedCall())

  t.is(i, 2)
})
