A pal requested me how I would resolve following drawback:
Given a string within the type "(1, 2, 3), (4, 5, 6), (7, 8, 9)"
, convert it to a multidimensional array of the shape [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
.
For my first move, I did some enjoyable shenanigans with Array.prototype.scale back()
and a few common expressions like this…
const listified = `(1, 2, 3), (4, 5, 6), (7, 8, 9), (5, junk, 100, 2eggs)`
.match(/((.*?))/g)
.scale back(
(a, c) => [
...a,
[
...c
.match(/([0-9]+)(?=[ ,)])/g)
.map((el) => !isNaN(el) && parseInt(el)),
],
],
[]
);
console.log(listified);
Whereas it appears to be like cool and looking out cool is my favourite factor about trendy JavaScript, this method does have one thing of an issue for calling loops inside loops, so here’s a extra environment friendly method that walks a pointer throughout the string and gathers up the numbers it finds into work units…
// Convert strings of the shape `"(1, 2, 3), (4, 5, 6), (7, 8, 9)"` into
// multidimensional arrays of the shape `[[1, 2, 3], [4, 5, 6], [7,8,9]]`.
const listifiedTokens = (str) => {
let knowledge = [];
let ws = [];
let x;
for (c of str) {
// Taking pains to stop type-coercsion.
if (!isNaN(c)) {
x = x ? `${x}${c}` : c;
}
// Begin a brand new work set and overwrite
// any current work set.
if (c === "(") {
ws = [];
}
// ')' and ',' terminate an inventory entry,
// and x have to be a quantity earlier than we parse.
if ([")", ","].contains(c) && !isNaN(x)) {
ws = [...ws, parseInt(x, 10)];
}
// Report the work set.
if (c === ")") {
knowledge = [...data, ws];
}
// Each time c is NaN, we flush x
// as a result of this solely occurs on the finish
// of a sound record or when the record merchandise
// incorporates an unsupported worth.
if (isNaN(c)) {
x = undefined;
}
}
return knowledge;
};
const str = `(1, 2, 3), (4, 5, 6), (7, 8, 8, 9), (100, 2egg, 5, bananas)`;
console.log(listifiedTokens(str));
It is not almost as cool trying, but it surely’s most likely higher in the long term.