What can you do with just one line of code? For the uninitiated, he may say that a line of code can print a log and calculate a value, but JavaScript can do a lot of complex things with just one line of code, and 1LOC has sorted out hundreds of functions that can be achieved with a single line of code, including arrays, DOM operations, object operations, etc., which is very practical!
For example:
Create an array of numbers within a given range
const range = (min, max) => [...Array(max - min + 1).keys()].map(i => i + min);// Orconst range = (min, max) => Array(max - min + 1).fill(0).map((_, i) => min + i);// Orconst range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i);// Examplerange(5, 10); // [5, 6, 7, 8, 9, 10]
- Serialize form data
const serialize = formEle => Array.from(new FormData(formEle)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v}), {});
- Get the time zone string
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;// ExamplegetTimezone(); // 'Asia/Saigon'
- Check if a value is a generator function
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;// ExamplegetTimezone(); // 'Asia/Saigon'
- Check if one rectangle overlaps the other
const overlaps = (a, b) => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);Get cookie valueconst cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();// Examplecookie('_ga'); // GA1.2.825309271.1581874719
Of course, from a practical point of view, what a single line of code can do is a bit one-sided, but there’s no denying that the examples provided by 1LOC are really useful, and learning them will make you look like an expert.