diff options
-rw-r--r-- | README.md | 17 | ||||
-rw-r--r-- | lib.c | 32 |
2 files changed, 43 insertions, 6 deletions
@@ -681,12 +681,23 @@ a = map(["foo", 1, true, null, 2.2], type); // a = ["string", "int", "bool", null, "double"] ``` -#### 6.22. `ord(s)` +#### 6.22. `ord(s, ...)` -Returns the byte value of the first character in the given string. +Without further arguments, this function returns the byte value of the first +character in the given string. + +If one or more index arguments are supplied, an array containing the byte +values at each given index is returned. If an invalid index is supplied, the +corresponding array entry will be `null`. Negative index entries are counted +towards the end of the string, e.g. `-2` will return the value of the second +last character. ```javascript -ord("Abc"); // 65 +ord("Abc"); // 65 +ord("Abc", 0); // [ 65 ] +ord("Abc", 1, -1); // [ 98, 99 ] +ord("Abc", 2, 1, 0); // [ 99, 98, 65 ] +ord("Abc", 10, -10, "nan"); // [ null, null, null ] ``` #### 6.23. `pop(arr)` @@ -831,17 +831,43 @@ static struct json_object * ut_ord(struct ut_state *s, uint32_t off, struct json_object *args) { struct json_object *obj = json_object_array_get_idx(args, 0); + struct json_object *rv, *pos; + size_t i, len, nargs; const char *str; + int64_t n; if (!json_object_is_type(obj, json_type_string)) return NULL; str = json_object_get_string(obj); + len = json_object_get_string_len(obj); - if (!str[0]) - return NULL; + nargs = json_object_array_length(args); + + if (nargs == 1) + return str[0] ? xjs_new_int64((int64_t)str[0]) : NULL; + + rv = xjs_new_array(); + + for (i = 1; i < nargs; i++) { + pos = json_object_array_get_idx(args, i); + + if (json_object_is_type(pos, json_type_int)) { + n = json_object_get_int64(pos); + + if (n < 0) + n += len; + + if (n >= 0 && n < len) { + json_object_array_add(rv, xjs_new_int64((int64_t)str[n])); + continue; + } + } - return xjs_new_int64((int64_t)str[0]); + json_object_array_add(rv, NULL); + } + + return rv; } static struct json_object * |