Issue
I'm going to answer my own question here because this is pretty difficult to Google and I want it to be easier for everyone to find.
This article explains what this pattern is:
An “options object” is a programming pattern that you can use to pass any number of named arguments to a function. Rather than using an ordered list of arguments, you simply pass one argument, which is an object containing named keys for all of your options. Keep reading to learn how and why.
You can use typescript features to implement this pattern in a more concise way. See my answer for how.
You can see a similar question about JavaScript here: Implement JavaScript options object parameter pattern?
This question is different because it's about TypeScript. There happens to be an answer on that JavaScript question that explains how to do it the typescript way, but I think it deserves its own question.
Solution
This is how, using destructuring, you can use the options object pattern in typescript (playground link):
interface Options {
lastSeparator?: string;
separatorBetweenArrayOfTwo?: string;
wrap?: (word: string) => string;
}
const separatedMessage = (
words: string[],
separator: string,
{
lastSeparator = separator,
separatorBetweenArrayOfTwo = lastSeparator,
wrap = (word: string): string => {
return word.toString();
}
}: Options = {} // the = {} at the end means you don't have to pass in an Object here if you don't want.
): string => {
let buf = '';
words.forEach((word, index, array) => {
if (index !== 0) {
if (array.length === 2) {
buf += separatorBetweenArrayOfTwo;
} else if (index === array.length - 1) {
buf += lastSeparator;
} else {
buf += separator;
}
}
buf += wrap(word);
});
return buf;
};
console.log(separatedMessage(["a", "b", "c", "d"], ", "))
console.log(separatedMessage(["a", "b"], ", ", {}))
console.log(separatedMessage(["a", "b"], ", ", {lastSeparator: ", and "}))
console.log(separatedMessage(["a", "b"], ", ", {lastSeparator: ", and ", separatorBetweenArrayOfTwo: " and "}))
This function lets you pass in an array of words and separate them with characters. You can optionally:
- Specify a different separator to use last:
, and
ina, b, c, and d
. - Specify a separator that's used for arrays of exactly two elements:
and
ina and b
but, and
ina, b, c, and d
. - Pass in a function that wraps each word in a string:
'
in'a', 'b', 'c', and 'd'
Answered By - Daniel Kaplan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.