Skip to content

Commit 722faf8

Browse files
committed
Implement String.prototype.trim()
JerryScript-DCO-1.0-Signed-off-by: Laszlo Vidacs [email protected]
1 parent 8a9633d commit 722faf8

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

jerry-core/ecma/builtin-objects/ecma-builtin-string-prototype.cpp

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
* limitations under the License.
1515
*/
1616

17+
#include <ctype.h>
1718
#include "ecma-alloc.h"
1819
#include "ecma-builtins.h"
1920
#include "ecma-conversion.h"
@@ -554,7 +555,62 @@ ecma_builtin_string_prototype_object_to_locale_upper_case (ecma_value_t this_arg
554555
static ecma_completion_value_t
555556
ecma_builtin_string_prototype_object_trim (ecma_value_t this_arg) /**< this argument */
556557
{
557-
ECMA_BUILTIN_CP_UNIMPLEMENTED (this_arg);
558+
ecma_completion_value_t ret_value = ecma_make_empty_completion_value ();
559+
560+
/* 1 */
561+
ECMA_TRY_CATCH (check_coercible_val,
562+
ecma_op_check_object_coercible (this_arg),
563+
ret_value);
564+
565+
/* 2 */
566+
ECMA_TRY_CATCH (to_string_val,
567+
ecma_op_to_string (this_arg),
568+
ret_value);
569+
570+
ecma_string_t *original_string_p = ecma_get_string_from_value (to_string_val);
571+
JERRY_ASSERT (ecma_string_get_length (original_string_p) >= 0);
572+
573+
/* 3 */
574+
const uint32_t len = (uint32_t) ecma_string_get_length (original_string_p);
575+
576+
uint32_t prefix = 0, postfix = 0;
577+
uint32_t new_len = 0;
578+
579+
while (prefix < len &&
580+
ecma_is_completion_value_empty (ret_value) &&
581+
isspace (ecma_string_get_char_at_pos (original_string_p, prefix)))
582+
{
583+
prefix++;
584+
}
585+
586+
while (postfix < len &&
587+
ecma_is_completion_value_empty (ret_value) &&
588+
isspace (ecma_string_get_char_at_pos (original_string_p, len-postfix-1)))
589+
{
590+
postfix++;
591+
}
592+
593+
new_len = len - prefix - postfix;
594+
595+
MEM_DEFINE_LOCAL_ARRAY (new_str_buffer, new_len + 1, ecma_char_t);
596+
597+
for (uint32_t idx = 0; idx < new_len; ++idx)
598+
{
599+
new_str_buffer[idx] = ecma_string_get_char_at_pos (original_string_p, idx + prefix);
600+
}
601+
602+
new_str_buffer[new_len] = '\0';
603+
ecma_string_t *new_str_p = ecma_new_ecma_string ((ecma_char_t *) new_str_buffer);
604+
605+
/* 4 */
606+
ret_value = ecma_make_normal_completion_value (ecma_make_string_value (new_str_p));
607+
608+
MEM_FINALIZE_LOCAL_ARRAY (new_str_buffer);
609+
610+
ECMA_FINALIZE (to_string_val);
611+
ECMA_FINALIZE (check_coercible_val);
612+
613+
return ret_value;
558614
} /* ecma_builtin_string_prototype_object_trim */
559615

560616
/**

0 commit comments

Comments
 (0)