summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorJo-Philipp Wich <jo@mein.io>2020-11-16 13:06:59 +0100
committerJo-Philipp Wich <jo@mein.io>2020-11-16 13:06:59 +0100
commit181fde5208efa0d45126327dd0c4197e1a63fd90 (patch)
tree73db9956175a741a9056ef086c0e616d6bc7836a
parent1e399df30ed1e8e1b2c609e90a152d6dab9977e1 (diff)
lib: extend length() to handle objects
Signed-off-by: Jo-Philipp Wich <jo@mein.io>
-rw-r--r--README.md19
-rw-r--r--lib.c12
2 files changed, 28 insertions, 3 deletions
diff --git a/README.md b/README.md
index 1a2051f..97fbe94 100644
--- a/README.md
+++ b/README.md
@@ -637,10 +637,23 @@ if the given argument is no object.
Convert the given string to lowercase and return the resulting string.
Returns `null` if the given argument could not be converted to a string.
-#### 6.18. `length(arr_or_str)`
+#### 6.18. `length(x)`
-Return the length of the given array or string. Returns `null` if the given
-argument is neither an array, nor a string.
+Return the length of the given object, array or string. Returns `null` if
+the given argument is neither an object, array, nor a string.
+
+For objects, the length is defined as the number of keys within the object,
+for arrays the length specifies the amount of contained items and for strings
+it represents the number of contained bytes.
+
+```javascript
+length("test") // 4
+length([true, false, null, 123, "test"]) // 5
+length({foo: true, bar: 123, baz: "test"}) // 3
+length({}) // 0
+length(true) // null
+length(10.0) // null
+```
#### 6.19. `log(x)`
diff --git a/lib.c b/lib.c
index f878d5c..af94e9a 100644
--- a/lib.c
+++ b/lib.c
@@ -368,8 +368,20 @@ static struct json_object *
ut_length(struct ut_state *s, uint32_t off, struct json_object *args)
{
struct json_object *arg = json_object_array_get_idx(args, 0);
+ size_t len;
switch (json_object_get_type(arg)) {
+ case json_type_object:
+ len = 0;
+
+ json_object_object_foreach(arg, k, v) {
+ (void)k;
+ (void)v;
+ len++;
+ }
+
+ return xjs_new_int64(len);
+
case json_type_array:
return xjs_new_int64(json_object_array_length(arg));