Skip to content

Commit

Permalink
fix: #75 twist 関数で文字列の前方一致していたところを、キーの前方一致判定に変更 (#76)
Browse files Browse the repository at this point in the history
* fix: #75 twist 関数で文字列の前方一致していたところを、キーの前方一致判定に変更

* Create khaki-sheep-roll.md
  • Loading branch information
mew-ton authored Dec 4, 2023
1 parent b0f20d0 commit aff83a1
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/khaki-sheep-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"json-origami": patch
---

fix: #75 twist 関数で文字列の前方一致していたところを、キーの前方一致判定に変更
9 changes: 8 additions & 1 deletion .vscode/project.code-workspace
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
{
"folders": [{ "path": ".." }]
"folders": [
{
"path": ".."
}
],
"settings": {
"typescript.tsdk": "node_modules/typescript/lib"
}
}
3 changes: 2 additions & 1 deletion src/twist.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fold } from './fold'
import { unfold } from './unfold'
import type { Dictionary, MoveMap, Twist, TwistOption } from './type'
import { includesKey } from './utils'

/**
*
Expand All @@ -16,7 +17,7 @@ export function twist<D extends Dictionary, M extends MoveMap<D>>(

const twisted = Object.fromEntries(
Object.entries(folded).map(([key, value]) => {
const found = Object.keys(moveMap).find((k) => key.startsWith(k))
const found = Object.keys(moveMap).find((k) => includesKey(key, k, option))

if (found) {
const newKey = key.replace(found, moveMap[found]!)
Expand Down
36 changes: 36 additions & 0 deletions test/twist.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,40 @@ describe('twist', () => {
}
})
})

// map データのキーが前方一致する組み合わせがある場合. e.g. foo.bar, foo.bar1
it('should be twisted correctly when the prefix is the same string.', () => {
const target = {
foo: {
bar: 0,
bar1: 1,
bar2: 2,
barbar: 3,
},
foo1: {
bar: 4,
bar1: 5,
bar2: 6
}
}

const map = {
'foo.bar': 'baz',
'foo.bar1': 'qux',
'foo.bar2': 'quux',
'foo.barbar': 'quux1'
}

expect(twist(target, map)).toEqual({
foo1: {
bar: 4,
bar1: 5,
bar2: 6
},
baz: 0,
qux: 1,
quux: 2,
quux1: 3
})
})
})

0 comments on commit aff83a1

Please sign in to comment.