mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-08 00:00:41 -04:00
3.0 KiB
3.0 KiB
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName |
|---|---|---|---|---|
| 594faaab4e2a8626833e9c3d | Tokenizzare una stringa con escaping | 1 | 302338 | tokenize-a-string-with-escaping |
--description--
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
Dovrebbe accettare tre parametri di input:
- The string
- The separator character
- The escape character
Dovrebbe produrre un elenco di stringhe.
Regole di suddivisione:
- The fields that were separated by the separators, become the elements of the output list.
- I campi vuoti dovrebbero essere preservati, anche all'inizio e alla fine.
Regole di escape:
- "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
- Quando il carattere di escape precede un carattere che non ha alcun significato speciale, conta ancora come un escape (ma non fa nulla di speciale).
- Ogni occorrenza del carattere di escape che è stato usato per evitare qualcosa, non dovrebbe diventare parte dell'output.
Dimostra che la tua funzione soddisfa il seguente caso di test:
Data la stringa
one^|uno||three^^^^|four^^^|^cuatro|
e usando | come separatore e ^ come carattere di escape la funzione dovrebbe produrre il seguente array:
['one|uno', '', 'three^^', 'four^|cuatro', '']
--hints--
tokenize dovrebbe essere una funzione.
assert(typeof tokenize === 'function');
tokenize dovrebbe restituire un array.
assert(typeof tokenize('a', 'b', 'c') === 'object');
tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^') dovrebbe restituire ['one|uno', '', 'three^^', 'four^|cuatro', '']
assert.deepEqual(tokenize(testStr1, '|', '^'), res1);
tokenize('a@&bcd&ef&&@@hi', '&', '@') dovrebbe restituire ['a&bcd', 'ef', '', '@hi']
assert.deepEqual(tokenize(testStr2, '&', '@'), res2);
--seed--
--after-user-code--
const testStr1 = 'one^|uno||three^^^^|four^^^|^cuatro|';
const res1 = ['one|uno', '', 'three^^', 'four^|cuatro', ''];
// TODO add more tests
const testStr2 = 'a@&bcd&ef&&@@hi';
const res2 = ['a&bcd', 'ef', '', '@hi'];
--seed-contents--
function tokenize(str, sep, esc) {
return true;
}
--solutions--
// tokenize :: String -> Character -> Character -> [String]
function tokenize(str, charDelim, charEsc) {
const dctParse = str.split('')
.reduce((a, x) => {
const blnEsc = a.esc;
const blnBreak = !blnEsc && x === charDelim;
const blnEscChar = !blnEsc && x === charEsc;
return {
esc: blnEscChar,
token: blnBreak ? '' : (
a.token + (blnEscChar ? '' : x)
),
list: a.list.concat(blnBreak ? a.token : [])
};
}, {
esc: false,
token: '',
list: []
});
return dctParse.list.concat(
dctParse.token
);
}