0

I have the following function:

export const getFormatValue = (raw, value) => {
 let maskIndex = 0;
 let formattedValue = '';
 raw.split('').forEach(char => {
 if (value.length > maskIndex && value[maskIndex] === ' ') {
 formattedValue += ' ';
 maskIndex += 1;
 }
 formattedValue += char;
 maskIndex += 1;
 });
 return formattedValue;
};

It fails the following test cases

Expected: "A BB CCC"
Received: "A B BC C C"
> 11 | expect(getFormatValue('ABBCCC', 'A AA AAA')).toBe('A BB CCC');

My code works for simple cases such as:

expect(getFormatValue('23', '0 0000 0000 0000')).toBe('2 3');

But soon as the "mask" pattern gets more complicated it fails.

The "mask" value is dynamic

asked Jun 23, 2022 at 14:00

2 Answers 2

1

You can reverse the string to be formatted, and then you can use the function Array.prototype.reduce and check the char in the pattern.

function getFormatValue(str, pattern) {
 const reversed = str.split("").reverse();
 return pattern.split("").reduce((a, c) => [...a, c === " " ? c : reversed.pop()], []).join("");
}
console.log(getFormatValue('ABBCCC', 'A AA AAA'));

answered Jun 23, 2022 at 14:29
Sign up to request clarification or add additional context in comments.

Comments

0

One simple way of doing this:

export const getFormatValue = (raw, value) => {
 raw = raw.split('');
 return value.replace(/[^\s]/g, () => {
 return raw.shift() || '';
 });
}
answered Jun 23, 2022 at 14:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.