diff --git a/.changeset/khaki-sheep-roll.md b/.changeset/khaki-sheep-roll.md new file mode 100644 index 0000000..f2dd8ef --- /dev/null +++ b/.changeset/khaki-sheep-roll.md @@ -0,0 +1,5 @@ +--- +"json-origami": patch +--- + +fix: #75 twist 関数で文字列の前方一致していたところを、キーの前方一致判定に変更 diff --git a/.vscode/project.code-workspace b/.vscode/project.code-workspace index 00603ec..1d7da00 100644 --- a/.vscode/project.code-workspace +++ b/.vscode/project.code-workspace @@ -1,3 +1,10 @@ { - "folders": [{ "path": ".." }] + "folders": [ + { + "path": ".." + } + ], + "settings": { + "typescript.tsdk": "node_modules/typescript/lib" + } } diff --git a/src/twist.ts b/src/twist.ts index 4cdbe9f..fecb421 100644 --- a/src/twist.ts +++ b/src/twist.ts @@ -1,6 +1,7 @@ import { fold } from './fold' import { unfold } from './unfold' import type { Dictionary, MoveMap, Twist, TwistOption } from './type' +import { includesKey } from './utils' /** * @@ -16,7 +17,7 @@ export function twist>( 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]!) diff --git a/test/twist.spec.ts b/test/twist.spec.ts index be565f7..2291bd9 100644 --- a/test/twist.spec.ts +++ b/test/twist.spec.ts @@ -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 + }) + }) })