From 49cfaca00882970c34e04fb2624f59171d6408f8 Mon Sep 17 00:00:00 2001 From: Fabian Steeg Date: Thu, 26 Sep 2024 11:47:23 +0200 Subject: [PATCH] Avoid collection and additional calls to `tail()` & `get()` (#127) --- .../java/org/metafacture/metafix/FixPath.java | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/metafix/src/main/java/org/metafacture/metafix/FixPath.java b/metafix/src/main/java/org/metafacture/metafix/FixPath.java index 0fe8357f..f493daca 100644 --- a/metafix/src/main/java/org/metafacture/metafix/FixPath.java +++ b/metafix/src/main/java/org/metafacture/metafix/FixPath.java @@ -278,18 +278,8 @@ else if (isReference(field)) { mode.apply(hash, field, newValue); } else { - if (!hash.containsField(field)) { - final Value value = Arrays.asList(ReservedField.$prepend.name(), ReservedField.$append.name()) - .contains(tail(path)[0]) ? Value.newArray() : Value.newHash(); - hash.put(field, value.withPathSet(newValue.getPath())); - } - else { - final Value value = hash.get(field); - if (value.isString()) { - hash.put(field, Value.newArray(a -> a.add(value))); - } - } - insertInto(hash.get(field), mode, newValue, field, tail(path)); + final String[] tail = tail(path); + insertInto(getContainerValue(hash, field, newValue.getPath(), tail[0]), mode, newValue, field, tail); } return new Value(hash); @@ -309,6 +299,23 @@ private Value insertInto(final Value value, final InsertMode mode, final Value n } } + private Value getContainerValue(final Hash hash, final String field, final String newPath, final String nextField) { + Value result = hash.get(field); + if (result == null) { + result = (nextField.equals(ReservedField.$prepend.name()) || nextField.equals(ReservedField.$append.name()) ? + Value.newArray() : Value.newHash()).withPathSet(newPath); + hash.put(field, result); + } + else { + if (result.isString()) { + final Value value = result; + result = Value.newArray(a -> a.add(value)); + hash.put(field, result); + } + } + return result; + } + private String[] tail(final String[] fields) { return Arrays.copyOfRange(fields, 1, fields.length); }