Skip to content

Commit

Permalink
custom contextSeparator fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Seva Denisov committed May 29, 2024
1 parent cb37162 commit 433d0ef
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ function mergeHashes(source, target, options = {}, resetValues = {}) {
const fullKeyPrefix = options.fullKeyPrefix || ''
const keySeparator = options.keySeparator || '.'
const pluralSeparator = options.pluralSeparator || '_'
const contextSeparator = options.contextSeparator || '_'

for (const key in source) {
const hasNestedEntries =
Expand Down Expand Up @@ -180,7 +181,7 @@ function mergeHashes(source, target, options = {}, resetValues = {}) {
const pluralMatch = key !== singularKey

// support for context in keys
const contextRegex = /_([^_]+)?$/
const contextRegex = new RegExp(`\\${contextSeparator}([^\\${contextSeparator}]+)?$`);
const contextMatch = contextRegex.test(singularKey)
const rawKey = singularKey.replace(contextRegex, '')

Expand Down
26 changes: 26 additions & 0 deletions test/helpers/mergeHashes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,19 @@ describe('mergeHashes helper function', () => {
done()
})

it('restores context keys when the singular one exists (custom contextSeparator)', (done) => {
const source = { key1: '', 'key1|context': 'value1' }
const target = { key1: '' }
const res = mergeHashes(source, target, { contextSeparator: '|' })

assert.deepEqual(res.new, { key1: '', 'key1|context': 'value1' })
assert.deepEqual(res.old, {})
assert.strictEqual(res.mergeCount, 1)
assert.strictEqual(res.pullCount, 1)
assert.strictEqual(res.oldCount, 0)
done()
})

it('does not restore context keys when the singular one does not', (done) => {
const source = { key1: '', key1_context: 'value1' }
const target = { key2: '' }
Expand All @@ -150,6 +163,19 @@ describe('mergeHashes helper function', () => {
done()
})

it('does not restore context keys when the singular one does not (custom contextSeparator)', (done) => {
const source = { key1: '', 'key1|context': 'value1' }
const target = { key2: '' }
const res = mergeHashes(source, target, { contextSeparator: '|' })

assert.deepEqual(res.new, { key2: '' })
assert.deepEqual(res.old, { key1: '', 'key1|context': 'value1' })
assert.strictEqual(res.mergeCount, 0)
assert.strictEqual(res.pullCount, 0)
assert.strictEqual(res.oldCount, 2)
done()
})

it('works with deep objects', (done) => {
const source = {
key1: 'value1',
Expand Down

0 comments on commit 433d0ef

Please sign in to comment.