After writing some code that is currently running, my next challenge involves re-factoring and tackling an issue related to scope. Specifically, I am working on retrieving message data and attempting to modify it in a more efficient manner:
function handleMessage(message) {
if(message.includes('dns')) {
// Extracting and reorganizing the desired data for API use
var buf1 = Buffer.allocUnsafe(26);
buf1 = message;
buf2 = buf1.slice(13, buf1.length);
message = buf2.toString('ascii', 0, buf2.length);
/* There might be a better approach using the Slack API in the future,
but this method works well for now.
Returns URL as a string without extra formatting.*/
var n = message.indexOf('|');
var o = message.indexOf('>');
var n = n+1;
var o = o-2;
var s1 = message.substr(n, o);
var p = s1.indexOf('>');
var s2 = s1.substr(0, p);
message = s2;
dnsLookup(message);
} else if(message.includes(' whois')) {
// Extracting and reorganizing desired data for API usage
var buf1 = Buffer.allocUnsafe(26);
buf1 = message;
buf2 = buf1.slice(13, buf1.length);
message = buf2.toString('ascii', 0, buf2.length);
var n = message.indexOf('|');
var o = message.indexOf('>');
var n = n+1;
var o = o-2;
var s1 = message.substr(n, o);
var p = s1.indexOf('>');
var s2 = s1.substr(0, p);
message = s2;
whoisLookup(message);
}
It's clear that there's repetition in the above code segment, and to address this, my goal is to create two separate functions from it. However, when trying to implement these functions within the existing function, it seems like the variable being passed isn't getting updated permanently (when checking the results of the first function before the second begins, it appears unchanged).
Is there a different perspective or approach I should consider in this situation? While combining everything into one function is an option, I'm aiming to prepare for potential future scenarios.
This is the revised version with my modifications included:
function handleMessage(message) {
function removeID(message) {
var buf1 = Buffer.allocUnsafe(26);
buf1 = message;
buf2 = buf1.slice(13, buf1.length);
message = buf2.toString('ascii', 0, buf2.length);
console.log(message);
}
function removeSlackURL(message){
console.log("test");
console.log(message);
var n = message.indexOf('|');
var o = message.indexOf('>');
var n = n+1;
var o = o-2;
var s1 = message.substr(n, o);
var p = s1.indexOf('>');
var s2 = s1.substr(0, p);
message = s2;
}
if(message.includes('dns')) {
// Take the data I want and re-organize for the API to use
// This removes the user ID text <@XXXXXXXXX>
removeID(message);
removeSlackURL(message);