Skip to content

Commit

Permalink
When result-matching, cache promises by the inputKey (#36)
Browse files Browse the repository at this point in the history
* When result-matching, cache promises by the inputKey

* Linting

* Restore old test
  • Loading branch information
flintinatux committed Jan 24, 2020
1 parent f7eda33 commit 7aaf58c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
8 changes: 5 additions & 3 deletions src/batch.js
Expand Up @@ -27,16 +27,18 @@ const batch = (opts={}, f) => {
matching ? (resolves[inputKey(arg)] = res) : resolves.push(res)

const batched = arg => {
if (uniq.has(arg)) {
return uniq.get(arg)
const cacheKey = matching ? inputKey(arg) : arg

if (uniq.has(cacheKey)) {
return uniq.get(cacheKey)
} else {
const promise = new Promise((res, rej) => {
args.push(arg)
rejects.push(rej)
addResolve(arg, res)
})

uniq.set(arg, promise)
uniq.set(cacheKey, promise)

if (args.length >= limit) run()

Expand Down
31 changes: 30 additions & 1 deletion test/batch.js
Expand Up @@ -4,7 +4,7 @@ const Spy = require('@articulate/spy')

const { identity, prop } = require('ramda')

const { batch, evolveP } = require('..')
const { batch, evolveP, mapP } = require('..')

describe('batch', () => {
const obj = { a: 'a', b: 'b', c: 'c' }
Expand Down Expand Up @@ -137,4 +137,33 @@ describe('batch', () => {
})
})
})

describe('with matching enabled and duplicate inputs', () => {
const input = [
{ id: 'a' },
{ id: 'b' },
{ id: 'a' }
]

const asyncListFn = () =>
(spy(), Promise.resolve([{ id: 'a', name: 'Spot' }]))

const batched =
batch({ inputKey: prop('id'), outputKey: prop('id') }, asyncListFn)

const test = mapP(batched)

beforeEach(() =>
test(input).then(res)
)

it('matches each result to the original input, accounting for duplicates', () => {
expect(spy.calls.length).to.equal(1)
expect(res()).to.eql([
{ id: 'a', name: 'Spot' },
undefined,
{ id: 'a', name: 'Spot' }
])
})
})
})

0 comments on commit 7aaf58c

Please sign in to comment.