Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace from an array of strings #2

Open
xthdraft opened this issue Nov 13, 2018 · 2 comments
Open

Replace from an array of strings #2

xthdraft opened this issue Nov 13, 2018 · 2 comments

Comments

@xthdraft
Copy link

It would be useful if the ReplaceAll method could accept an array.

As an example, I altered the ReplaceAll code to produce this:
// from javascript call as: sb.replaceFromArray()

napi_value ReplaceFromArray(napi_env env, napi_callback_info info){
size_t argsLength = 1;
napi_value args[2]; // will hold parameters from a 2d array during a for loop
napi_value me;
int n;

	// test with hard-coded array containing 2 pairs of strings
	//  "john is some writer"  => "john is this joke"
    const char* arr[][2] = {{"some", "this"},
		                    {"writer", "joke"}};

   
    napi_get_cb_info(env, info, &argsLength, args, &me, 0);  // place input parameters into args[]
    /* if (argsLength < 2){  // this bit no longer needed
         return me;
   */
    uint16_t* buffer;
    int64_t* metadata;
    getBufferAndMetaData(env, me, &buffer, &metadata);
    uint16_t* pattern;
    int64_t patternLength;
    bool patternFreeAble;
    for (n = 0; n < 2;  n++ )    
	{
	 	napi_create_string_utf8(env, arr[n][0],
                                 NAPI_AUTO_LENGTH ,
                                 &args[0]);

		napi_create_string_utf8(env, arr[n][1],
                                 NAPI_AUTO_LENGTH ,
                                 &args[1]);
              // .....  the rest of the replaceAll code
            }
        return me;

}

I also note that the main section from replaceAll is mostly identical to that inside the ReplacePattern function. There is a potential therefore for refactoring, by which this section could be called from a separate function.

A more sophisticated implementation of ReplaceFromArray() would pass the array as a parameter, although embedding a hard-coded array has the advantage of "hiding" the array contents, while still suiting many possible applications.

@magiclen
Copy link
Owner

In your case, the array can be easily used in JavaScript with a for loop or the forEach function.

let arr = [['some', 'this'], ['writer', 'joke']];
arr.forEach(function(e) {
    sb.replaceAll(e[0], e[1]);
});

@xthdraft
Copy link
Author

xthdraft commented Nov 13, 2018 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants