LibJS: Add String.prototype.concat
This commit is contained in:
parent
e72a537033
commit
7725b1970e
Notes:
sideshowbarker
2024-07-19 07:33:02 +09:00
Author: https://github.com/kessejones Commit: https://github.com/SerenityOS/serenity/commit/7725b1970e5 Pull-request: https://github.com/SerenityOS/serenity/pull/1817 Reviewed-by: https://github.com/awesomekling
3 changed files with 42 additions and 0 deletions
Libraries/LibJS
|
@ -55,6 +55,7 @@ StringPrototype::StringPrototype()
|
|||
put_native_function("trim", trim, 0);
|
||||
put_native_function("trimStart", trim_start, 0);
|
||||
put_native_function("trimEnd", trim_end, 0);
|
||||
put_native_function("concat", concat, 1);
|
||||
}
|
||||
|
||||
StringPrototype::~StringPrototype()
|
||||
|
@ -307,4 +308,22 @@ Value StringPrototype::trim_end(Interpreter& interpreter)
|
|||
return trim_string(interpreter, *this_object, TrimMode::Right);
|
||||
}
|
||||
|
||||
Value StringPrototype::concat(Interpreter& interpreter)
|
||||
{
|
||||
auto* this_object = interpreter.this_value().to_object(interpreter.heap());
|
||||
if (!this_object)
|
||||
return {};
|
||||
auto& string = this_object->to_string().as_string()->string();
|
||||
|
||||
StringBuilder builder;
|
||||
builder.append(string);
|
||||
|
||||
for (size_t i = 0; i < interpreter.argument_count(); ++i) {
|
||||
auto string_argument = interpreter.argument(i).to_string();
|
||||
builder.append(string_argument);
|
||||
}
|
||||
|
||||
return js_string(interpreter, builder.to_string());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -53,6 +53,7 @@ private:
|
|||
static Value trim(Interpreter&);
|
||||
static Value trim_start(Interpreter&);
|
||||
static Value trim_end(Interpreter&);
|
||||
static Value concat(Interpreter&);
|
||||
};
|
||||
|
||||
}
|
||||
|
|
22
Libraries/LibJS/Tests/String.prototype.concat.js
Normal file
22
Libraries/LibJS/Tests/String.prototype.concat.js
Normal file
|
@ -0,0 +1,22 @@
|
|||
load("test-common.js");
|
||||
|
||||
try {
|
||||
assert(String.prototype.concat.length === 1);
|
||||
assert("".concat(1) === "1");
|
||||
assert("".concat(3,2,1) === "321");
|
||||
assert("hello".concat(" ", "friends") === "hello friends");
|
||||
assert("".concat(null) === "null");
|
||||
assert("".concat(false) === "false");
|
||||
assert("".concat(true) === "true");
|
||||
assert("".concat([]) === "");
|
||||
assert("".concat([1, 2, 3, 'hello']) === "1,2,3,hello");
|
||||
assert("".concat(true, []) === "true");
|
||||
assert("".concat(true, false) === "truefalse");
|
||||
assert("".concat({}) === "[object Object]");
|
||||
assert("".concat(1, {}) === "1[object Object]");
|
||||
assert("".concat(1, {}, false) === "1[object Object]false");
|
||||
|
||||
console.log("PASS");
|
||||
} catch (err) {
|
||||
console.log("FAIL: " + err);
|
||||
}
|
Loading…
Add table
Reference in a new issue