LibJS: Add String.prototype.includes

This commit is contained in:
Kesse Jones 2020-04-25 09:59:22 -03:00 committed by Andreas Kling
parent 4a37362249
commit 838127df35
Notes: sideshowbarker 2024-07-19 07:18:16 +09:00
3 changed files with 48 additions and 0 deletions

View file

@ -57,6 +57,7 @@ StringPrototype::StringPrototype()
put_native_function("trimEnd", trim_end, 0);
put_native_function("concat", concat, 1);
put_native_function("substring", substring, 2);
put_native_function("includes", includes, 1);
}
StringPrototype::~StringPrototype()
@ -368,4 +369,32 @@ Value StringPrototype::substring(Interpreter& interpreter)
return js_string(interpreter, string_part);
}
Value StringPrototype::includes(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();
auto search_string = interpreter.argument(0).to_string();
i32 position = 0;
if (interpreter.argument_count() >= 2) {
position = interpreter.argument(1).to_i32();
if (position >= static_cast<i32>(string.length()))
return Value(false);
if (position < 0)
position = 0;
}
if (position == 0)
return Value(string.contains(search_string));
auto substring_length = string.length() - position;
auto substring_search = string.substring(position, substring_length);
return Value(substring_search.contains(search_string));
}
}

View file

@ -55,6 +55,7 @@ private:
static Value trim_start(Interpreter&);
static Value trim_end(Interpreter&);
static Value concat(Interpreter&);
static Value includes(Interpreter&);
};
}

View file

@ -0,0 +1,18 @@
load("test-common.js");
try {
assert(String.prototype.includes.length === 1);
assert("hello friends".includes("hello") === true);
assert("hello friends".includes("hello", 100) === false);
assert("hello friends".includes("hello", -10) === true);
assert("hello friends".includes("friends", 6) === true);
assert("hello friends".includes("hello", 6) === false);
assert("hello friends false".includes(false) === true);
assert("hello 10 friends".includes(10) === true);
assert("hello friends undefined".includes() === true);
console.log("PASS");
} catch (err) {
console.log("FAIL: " + err);
}