3.0 KiB
3.0 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
594faaab4e2a8626833e9c3d | Tokenizzare una stringa con escaping | 5 | 302338 | tokenize-a-string-with-escaping |
--description--
Scrivi una funzione o un programma che può dividere una stringa ad ogni occorrenza di un carattere separatore (salvo escape).
Dovrebbe accettare tre parametri di input:
- La stringa
- Il carattere separatore
- Il carattere di escape
Dovrebbe produrre un elenco di stringhe.
Regole di suddivisione:
- I campi separati dai separatori diventano gli elementi della lista di output.
- I campi vuoti dovrebbero essere preservati, anche all'inizio e alla fine.
Regole di escape:
- "Fare l'escape" significa far precedere il carattere da una occorrenza del carattere di escape.
- 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
);
}