Skip to content

Commit

Permalink
introduce a moveField jsonata function #126
Browse files Browse the repository at this point in the history
  • Loading branch information
aeberhart committed Mar 31, 2022
1 parent 995163e commit eb1ec60
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 0 deletions.
51 changes: 51 additions & 0 deletions dashjoin-core/src/main/java/org/dashjoin/function/MoveField.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package org.dashjoin.function;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* $moveField(object, from, to) removes the key "from" from object and inserts it in "to". If to is
* an object, the removed key is added to it. If to is an array, the removed key is added to each
* array element (if that is an object)
*/
@SuppressWarnings("rawtypes")
public class MoveField extends AbstractVarArgFunction<Object> {

@SuppressWarnings("unchecked")
@Override
public Object run(List arg) throws Exception {

Map object = (Map) arg.get(0);
String from = (String) arg.get(1);
String to = (String) arg.get(2);
Object f = object.remove(from);
Object t = object.get(to);
if (t instanceof List) {
List l = (List) t;
for (Object i : l)
if (i instanceof Map)
((Map) i).put(from, f);
}
if (t instanceof Map) {
Map m = (Map) t;
m.put(from, f);
}
return object;
}

@Override
public String getID() {
return "moveField";
}

@Override
public String getType() {
return "read";
}

@Override
public List<Class> getArgumentClassList() {
return Arrays.asList(Object.class, String.class, String.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ org.dashjoin.function.Index
org.dashjoin.function.Table2Object
org.dashjoin.function.IsRecursiveTrigger
org.dashjoin.function.Excel2data
org.dashjoin.function.MoveField
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.dashjoin.function;

import static java.util.Arrays.asList;
import static org.dashjoin.util.MapUtil.of;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class MoveFieldTest {

@Test
public void testIgoreIfToIsNoObject() throws Exception {
MoveField m = new MoveField();
Object res = m.run(Arrays.asList(of("x", 1, "y", asList(1)), "x", "y"));
Assertions.assertEquals("{y=[1]}", "" + res);
}

@Test
public void testMoveToArray() throws Exception {
MoveField m = new MoveField();
Object res = m.run(Arrays.asList(of("x", 1, "y", asList(of(), of())), "x", "y"));
Assertions.assertEquals("{y=[{x=1}, {x=1}]}", "" + res);
}

@Test
public void testMoveToMap() throws Exception {
MoveField m = new MoveField();
Object res = m.run(Arrays.asList(of("x", 1, "y", of()), "x", "y"));
Assertions.assertEquals("{y={x=1}}", "" + res);
}
}

0 comments on commit eb1ec60

Please sign in to comment.