Is it possible to convert the following to an in-line expression?
const
rePlace = (count) => (m) => {
count ++;
return (parseInt(m) > 255 || count > 4) ? '<invalid>' : m;
},
regex = /\d+(?=(\.|$))/g,
potential_ips = ['1.2.3.4.5', '12.34.45.56', '123.456.789.0', '1.2.3.4.5.6'];
for (let ip of potential_ips) {
ip = ip.replace(regex, rePlace(0));
console.log(ip);
}
My first attempt was to call the function with (0) as a parameter, but I think on successive calls it fails:
regex = /\d+(?=(\.|$))/g;
potential_ips = ['1.2.3.4.5', '12.34.45.56', '123.456.789.0', '1.2.3.4.5.6'] ;
for (let ip of potential_ips) {
ip = ip.replace(regex, ((count) => (m) => count++, (parseInt(m) > 255 || count > 4) ? '<invalid>' : m)(0));
console.log(ip);
}
Is there a way to do this, or not possible?
const potential_ips = [
'1.2.3.4.5',
'12.34.45.56',
'123.456.789.0',
'1.2.3.4.5.6',
'::0',
'www.google.com'
];
for (const ip of potential_ips) {
console.log(
ip.split('.')
.map((m,i) => (parseInt(m) <= 255 && parseInt(m) >= 0 && i < 4) ? m : '<invalid>')
.join('.')
);
}
Here's the original, but with traditional function functions:
const
rePlace = function(count) {
return function(segment) {
count ++;
return (parseInt(segment) > 255 || count > 4) ? '<invalid>' : segment;
};
},
regex = /\d+(?=(\.|$))/g,
potential_ips = ['1.2.3.4.5', '12.34.45.56', '123.456.789.0', '1.2.3.4.5.6'];
for (let ip of potential_ips) {
ip = ip.replace(regex, rePlace(0));
console.log(ip);
}
It might be a little clearer expressed that way.