From 7162ae8c641314846f0b565d7614ac8d71dbd628 Mon Sep 17 00:00:00 2001 From: Charlie Stanton Date: Sun, 7 Apr 2024 16:04:23 +0100 Subject: Add merge command --- main/command.go | 34 ++++++++++++++++++++++++++++++++++ main/main_test.go | 5 +++++ main/parse.go | 2 ++ 3 files changed, 41 insertions(+) (limited to 'main') diff --git a/main/command.go b/main/command.go index 3f22821..6d75974 100644 --- a/main/command.go +++ b/main/command.go @@ -44,13 +44,47 @@ func (cmd AppendNextCommand) exec(state *ProgramState) { if err != nil { panic("Missing next value") } + + state.prevStart = nextItem.PrevStart + state.start = nextItem.Start + state.end = nextItem.End + state.nextEnd = nextItem.NextEnd + state.value = append(state.value, nextItem.Value) + state.pc++ } func (cmd AppendNextCommand) String() string { return "N" } +type MergeCommand struct {} +func (cmd MergeCommand) exec(state *ProgramState) { + nextItem, err := state.in.Read() + if err != nil { + panic("Missing next value") + } + + state.prevStart = nextItem.PrevStart + state.start = nextItem.Start + state.end = nextItem.End + state.nextEnd = nextItem.NextEnd + + if len(state.value) == 0 { + state.value = []walk.Value {nextItem.Value} + } else { + state.value = append( + state.value[:len(state.value) - 1], + walk.Merge(state.value[len(state.value) - 1], nextItem.Value)... + ) + } + + state.pc++ +} +func (cmd MergeCommand) String() string { + return "m" +} + type DeleteValueCommand struct {} func (cmd DeleteValueCommand) exec(state *ProgramState) { state.value = nil diff --git a/main/main_test.go b/main/main_test.go index 7aa90aa..74f179b 100644 --- a/main/main_test.go +++ b/main/main_test.go @@ -64,6 +64,11 @@ func TestMain(t *testing.T) { input: miscInput, expected: `["Charlie Johnson","Tom Johnson","Charlie Chaplin","John Johnson"]`, }, + { + program: "s/#(\"people\" @(. #(\"first_name\" .)#)@)#/{ ms/#(\"people\" @(. (#(\"first_name\" \".{-0}$a\" \"last_name\" \".{-0}$b\")#$_) `#(\"name\" \"$a $b\")#`)@)#/ }", + input: miscInput, + expected: `{"something":{"nested":"Here is my test value"},"array":["Hello","world","these","are","values"],"people":[{"name":"Charlie Johnson","age":22},{"name":"Tom Johnson","age":18},{"name":"Charlie Chaplin","age":122},{"name":"John Johnson","age":48}]}`, + }, } for i, test := range tests { diff --git a/main/parse.go b/main/parse.go index 3e0e80b..3c24e6c 100644 --- a/main/parse.go +++ b/main/parse.go @@ -69,6 +69,8 @@ func (p *parser) parseBasicCommand(commands []Command, commandChar rune) []Comma return append(commands, NextCommand{}) case 'N': return append(commands, AppendNextCommand{}) + case 'm': + return append(commands, MergeCommand{}) case 's': ast := p.parseSubex() subex := subex.CompileTransducer(ast) -- cgit v1.2.3