Home > Net >  Javascript - Parse string based upon keys in dictionary / object
Javascript - Parse string based upon keys in dictionary / object

Time:04-19

In my React program, suppose I had the following dictionary / object

const myDict = {
    "a":"Value 1",
    "b":"Value 2",
    "hello":"Value 3",
    "Bye":"Value 4"
}

(note that no keys have values existing in any other keys - For example, no key can contain the a letter since that is a different key)

And I will be receiving a string that will ONLY CONSIST OF PERMUTATIONS OF THE KEYS TO THIS OBJECT, so, for example, possible string entries will be:

  • "abhellob"
  • "ababByeahello"
  • "ByehelloByeba"
  • etc.

And I am looking to create a function that will break the input string down into its constituent parts based upon the keys of myDict.

So, for example,

  • "abhellob" would become ["a", "b", "hello", "b"]

How can I create such a function? I've tried, but am getting lost with having to deal with different length keys to myDict and I don't know how to do it.

CodePudding user response:

A regular expression that alternates between the different keys would do the trick.

const myDict = {
    "a":"Value 1",
    "b":"Value 2",
    "hello":"Value 3",
    "Bye":"Value 4"
}
const pattern = new RegExp(
  Object.keys(myDict).join('|'),
  'g'
);
console.log("abhellob".match(pattern));
console.log("ababByeahello".match(pattern));
console.log("ByehelloByeba".match(pattern));

(If some keys could have character overlap, a start would be to sort the keys so the longest ones come first.)

const myDict = {
    "a":"Value 1",
    "b":"Value 2",
    "hello":"Value 3",
    "Bye":"Value 4"
}
const pattern = new RegExp(
  Object.keys(myDict)
    .sort((a, b) => a.length - b.length)
    .join('|'),
  'g'
);
console.log("abhellob".match(pattern));
console.log("ababByeahello".match(pattern));
console.log("ByehelloByeba".match(pattern));

CodePudding user response:

You can do this without Regex:

function getFragments(entryString){
  const myDict = {
"a":"Value 1",
"b":"Value 2",
"hello":"Value 3",
"Bye":"Value 4"
  }
  const keys = Object.keys(myDict);
  
  const result = [];
  let remainingString = entryString;
  while (remainingString) {
const nextWord = keys.find(key => remainingString.startsWith(key));
if (!nextWord) throw new Error("Couldn't match with word");

result.push(nextWord);
remainingString = remainingString.slice(nextWord.length);
  }
  
  return result;
}

console.log(getFragments("abhellob"));
console.log(getFragments("ababByeahello"));
console.log(getFragments("ByehelloByeba"));

  • Related