10 one-liner JavaScript codes that showcase some clever and efficient programming techniques:
- Generate an array of numbers from
a
tob
:
const range = (a, b) => Array.from({length: b - a + 1}, (_, i) => i + a);
- Check if a string is empty or null:
isEmptyOrNull(str) { return !str || str.trim() === ''; }
- Reverse an array without modifying the original one (deep copy):
const reverseArray = arr => [...arr].reverse();
- Flatten nested arrays to a single level using recursion and
reduce
:
flatten(arr) { return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []); }
- Convert an object into its JSON string representation (deep copy):
toJsonString(obj) { return JSON.stringify(JSON.parse(JSON.stringify(obj))); }
- Check if a given character is present in the second half of strings:
isCharInSecondHalf(str, char) { const mid = str.length / 2; return str.substring(mid).includes(char); }
- Swap two variables without using an extra variable (destructuring):
swap(a, b) { [a, b] = [b, a]; }
- Count the number of words in all strings within nested arrays:
countWords(arrays) { return [].concat(...arrays).reduce((total, str) => total + (str.split(/\s+/g)?.length || 0), 0); }
- Remove falsy values from an array using
filter
method and default object properties access (__valueOf()
) for primitives:
removeFalsy(arr) { return arr.filter(item => !!item); } // Simplified, JavaScript already does this with filter()
- Create a new Date object based on the current time plus seconds passed as input (using destructuring and spread operator):
newDateWithSeconds(currentTimeInMs = performance.now(), secsPassed) { return new Date(currentTimeInMs + secsPassed * 1000); }
These snippets demonstrate various JavaScript techniques, including ES6 features like arrow functions, template literals, array methods (such as map
, reduce
), destructuring assignment, and the spread operator. Note that some of these one-liners are more about illustrating best practices or clever tricks rather than being directly applicable in a production environment without context. Always consider readability when writing code for real-world applications!