new class js -advanced
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
// some, but not all fields are quoted - solution 1
|
||||
|
||||
const mixedCSV =
|
||||
'"very big, soft computer mouse","the cutest peripheral ever",10,39.90';
|
||||
|
||||
let fields = [];
|
||||
let index = 0;
|
||||
let state = 'outside';
|
||||
|
||||
mixedCSV.split('').forEach((char) => {
|
||||
if (state === 'quoted') {
|
||||
fields[index] += char; // => [",v,e,r,y..."]
|
||||
if (char === '"') {
|
||||
state = 'outside';
|
||||
index += 1;
|
||||
}
|
||||
} else if (state === 'unquoted') {
|
||||
if (char === ',') {
|
||||
state = 'outside';
|
||||
index += 1;
|
||||
} else {
|
||||
fields[index] += char;
|
||||
}
|
||||
} else if (state === 'outside') {
|
||||
fields[index] = char; //=> [",...
|
||||
if (char === '"') {
|
||||
state = 'quoted';
|
||||
} else if (char !== ',') {
|
||||
state = 'unquoted';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
console.log(fields);
|
||||
@@ -0,0 +1,28 @@
|
||||
// some, but not all fields are quoted - solution 2/2
|
||||
|
||||
const mixedCSV =
|
||||
'"very big, soft computer mouse",' + '"the cutest peripheral ever",10,39.90';
|
||||
|
||||
let fields = [];
|
||||
|
||||
const mixedCSVToArray = (s) =>
|
||||
findCommaPositions(',' + s + ',')
|
||||
.map((position, i, positions) => s.slice(position, positions[i + 1] - 1))
|
||||
.slice(0, -1);
|
||||
|
||||
const findCommaPositions = (s) =>
|
||||
s
|
||||
.split('')
|
||||
.reduce(
|
||||
(positions, char, position) =>
|
||||
char === ',' && isEven(countQuotes(s.slice(0, position)))
|
||||
? positions.concat(position)
|
||||
: positions,
|
||||
[]
|
||||
);
|
||||
|
||||
const countQuotes = (s) => s.split('').filter((c) => c === '"').length;
|
||||
|
||||
const isEven = (num) => num % 2 === 0;
|
||||
|
||||
console.log(mixedCSVToArray(mixedCSV));
|
||||
Reference in New Issue
Block a user