URLSearchParamsIterator.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Array.h>
  7. #include <LibJS/Runtime/IteratorOperations.h>
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/Bindings/URLSearchParamsIteratorPrototype.h>
  10. #include <LibWeb/URL/URLSearchParamsIterator.h>
  11. namespace Web::Bindings {
  12. template<>
  13. void Intrinsics::create_web_prototype_and_constructor<URLSearchParamsIteratorPrototype>(JS::Realm& realm)
  14. {
  15. auto prototype = heap().allocate<URLSearchParamsIteratorPrototype>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors();
  16. m_prototypes.set("URLSearchParamsIterator"sv, prototype);
  17. }
  18. }
  19. namespace Web::URL {
  20. WebIDL::ExceptionOr<JS::NonnullGCPtr<URLSearchParamsIterator>> URLSearchParamsIterator::create(URLSearchParams const& url_search_params, JS::Object::PropertyKind iteration_kind)
  21. {
  22. return MUST_OR_THROW_OOM(url_search_params.heap().allocate<URLSearchParamsIterator>(url_search_params.realm(), url_search_params, iteration_kind));
  23. }
  24. URLSearchParamsIterator::URLSearchParamsIterator(URLSearchParams const& url_search_params, JS::Object::PropertyKind iteration_kind)
  25. : PlatformObject(url_search_params.realm())
  26. , m_url_search_params(url_search_params)
  27. , m_iteration_kind(iteration_kind)
  28. {
  29. }
  30. URLSearchParamsIterator::~URLSearchParamsIterator() = default;
  31. JS::ThrowCompletionOr<void> URLSearchParamsIterator::initialize(JS::Realm& realm)
  32. {
  33. MUST_OR_THROW_OOM(Base::initialize(realm));
  34. set_prototype(&Bindings::ensure_web_prototype<Bindings::URLSearchParamsIteratorPrototype>(realm, "URLSearchParamsIterator"));
  35. return {};
  36. }
  37. void URLSearchParamsIterator::visit_edges(JS::Cell::Visitor& visitor)
  38. {
  39. Base::visit_edges(visitor);
  40. visitor.visit(m_url_search_params);
  41. }
  42. JS::Object* URLSearchParamsIterator::next()
  43. {
  44. if (m_index >= m_url_search_params->m_list.size())
  45. return create_iterator_result_object(vm(), JS::js_undefined(), true);
  46. auto& entry = m_url_search_params->m_list[m_index++];
  47. if (m_iteration_kind == JS::Object::PropertyKind::Key)
  48. return create_iterator_result_object(vm(), JS::PrimitiveString::create(vm(), entry.name), false);
  49. else if (m_iteration_kind == JS::Object::PropertyKind::Value)
  50. return create_iterator_result_object(vm(), JS::PrimitiveString::create(vm(), entry.value), false);
  51. return create_iterator_result_object(vm(), JS::Array::create_from(realm(), { JS::PrimitiveString::create(vm(), entry.name), JS::PrimitiveString::create(vm(), entry.value) }), false);
  52. }
  53. }