Skip to content

Commit 7aff4be

Browse files
committed
Fixed the problem of invalid identifiers in maps.
1 parent 9ffc4f4 commit 7aff4be

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/main/java/com/diffplug/jscriptbox/JScriptBox.java

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,21 @@ public static JScriptBox create() {
3434
return new JScriptBox();
3535
}
3636

37-
/** Sets all of the properties contained in the given map. */
37+
/** Sets all of the properties contained in the given map. Throws an error if one of the entry keys isn't a valid identifier. */
3838
public JScriptBox setAll(Map<String, ?> map) {
39-
names.putAll(map);
39+
for (Map.Entry<String, ?> entry : map.entrySet()) {
40+
set(entry.getKey()).toValue(entry.getValue());
41+
}
42+
return this;
43+
}
44+
45+
/** Sets all of the properties contained in the given map for which the key is a valid identifier. */
46+
public JScriptBox setAllValid(Map<String, ?> map) {
47+
for (Map.Entry<String, ?> entry : map.entrySet()) {
48+
if (isValidIdentifier(entry.getKey())) {
49+
set(entry.getKey()).toValue(entry.getValue());
50+
}
51+
}
4052
return this;
4153
}
4254

@@ -47,13 +59,17 @@ public NameSetter set(String name) {
4759

4860
/** Checks that the given name is a valid identifier. */
4961
static String checkValidIdentifier(String name) {
50-
Check.that(name.length() > 0 &&
51-
Character.isJavaIdentifierStart(name.codePointAt(0)) &&
52-
name.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart),
53-
"'%0' is not a valid identifier", name);
62+
Check.that(isValidIdentifier(name), "'%0' is not a valid identifier", name);
5463
return name;
5564
}
5665

66+
/** Checks that the given name is a valid identifier. */
67+
static boolean isValidIdentifier(String name) {
68+
return name.length() > 0 &&
69+
Character.isJavaIdentifierStart(name.codePointAt(0)) &&
70+
name.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
71+
}
72+
5773
/** Fluent API for setting names in this JsHarness. */
5874
public class NameSetter {
5975
private final String name;

0 commit comments

Comments
 (0)