static void KNearestWithin()

in src/maluuba/speech/nodejs/fuzzymatcher.hpp [459:507]


    static void KNearestWithin(const v8::FunctionCallbackInfo<v8::Value>& args)
    {
      auto isolate = args.GetIsolate();
      v8::Local<v8::Context> context = isolate->GetCurrentContext();

      if (args.Length() < 3) {
        isolate->ThrowException(v8::Exception::TypeError(
            v8::String::NewFromUtf8(isolate, "Expected 3 arguments.")));
        return;
      }

      if (!args[1]->IsUint32()) {
        isolate->ThrowException(v8::Exception::TypeError(
            v8::String::NewFromUtf8(isolate, "Expected argument to be an integer.")));
        return;
      }
      if (!args[2]->IsNumber()) {
        isolate->ThrowException(v8::Exception::TypeError(
            v8::String::NewFromUtf8(isolate, "Expected argument to be a number.")));
        return;
      }

      auto obj = ObjectWrap::Unwrap<FuzzyMatcher>(args.Holder());
      double threshold_scale;
      auto target = obj->to_target(isolate, args[0], threshold_scale);
      auto k = args[1]->Uint32Value(context).ToChecked();
      auto threshold = args[2]->NumberValue(context).ToChecked() * threshold_scale;

      try {
        auto matches = obj->matcher().find_k_nearest_within(target, k, threshold);

        auto context = isolate->GetCurrentContext();
        auto wrap_matches = v8::Array::New(isolate, matches.size());
        for (size_t i = 0; i < matches.size(); ++i) {
          speech::FuzzyMatcher<NodeJsTarget>::Match match(matches[i].element().target, matches[i].distance() / threshold_scale);
          auto wrap_match = new Match(std::move(match));

          const auto argc = 1;
          v8::Local<v8::Value> argv[argc] = { v8::External::New(isolate, wrap_match) };
          auto instance = Match::constructor(isolate)->NewInstance(context, argc, argv).ToLocalChecked();
          wrap_matches->Set(i, instance);
        }
        args.GetReturnValue().Set(wrap_matches);
      } catch(const std::exception& e) {
        isolate->ThrowException(v8::Exception::Error(
            v8::String::NewFromUtf8(isolate, e.what())));
        return;
      }
    }