top of page

JavaScript One-Liner coding/ Programming



1. How to convert a string from snake_case to camelcase

A string in snake_case uses the underscore character to separate each word. Each word in a snake_case string usually begins with a lowercase letter, although variants exist. A camelCase string begins with a lowercase letter, each following word beginning with an uppercase letter. There are no intervening spaces or punctuation in a camelCase string.


const str = 'The Tech Platform';
const toCamelCase = (str = '') => {
   return str
      .replace(/[^a-z0-9]/gi, ' ')
      .toLowerCase()
      .split(' ')
      .map((el, ind) => ind === 0 ? el : el[0].toUpperCase() + el.substring(1, el.length))
      .join('');
};
console.log(toCamelCase(str));

Output:




2. How to find the Minimum Value and Maximum Value of an array


const arr = [56, 34, 23, 687, 2, 56, 567];
const findMinMax = (arr = []) => {
   const creds = arr.reduce((acc, val) => {
   let [smallest, greatest] = acc;
      if(val > greatest){
         greatest = val;
      };
      if(val < smallest){
         smallest = val;
      };
      return [smallest, greatest];
   }, [Infinity, -Infinity]);
   return creds;
};
console.log(findMinMax(arr));

Output:




3. How to detect mark mode using javascript

With code running in a web browser, you can detect dark mode using the following one-liner:


const darkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log(darkMode);



4. How to detect an browser Name using javascript

You can check which browser is running on your computer using this simple regular expression match:


function fnBrowserDetect(){let userAgent = navigator.userAgent;let browserName;if(userAgent.match(/chrome|chromium|crios/i)){
             browserName = "chrome";}else if(userAgent.match(/firefox|fxios/i)){
             browserName = "firefox";}  else if(userAgent.match(/safari/i)){
             browserName = "safari";}else if(userAgent.match(/opr\//i)){
             browserName = "opera";} else if(userAgent.match(/edg/i)){
             browserName = "edge";}else{
             browserName="No browser detection";}
         
          document.querySelector("h1").innerText="You are using "+ browserName +" browser";}



5. How to check if an array is empty

An array is empty if there are no elements in it. You can check if an array is empty using the following code:


//JavaScript Function 
function isEmptyArray(arr){
if(Array.isArray(arr))
  {
    if(arr.length === 0)
      {
        document.write("Given Array is empty"); //if array is an array and array is empty 
      }
    else
      {
        document.write("Given array is not empty"); // if array is an array but is not empty
      }
  }
else
  {
  document.write("Given variable is not an array"); //if given array is not  array 
  }
}
//checking all three conditions
var arr1 = [10,20,30];
isEmptyArray(arr1);
console.log("Array is",  arr1 , "\n");
var arr2 = [];
isEmptyArray(arr2);
console.log("Array is",  arr2 , "\n");
var string = "CodesDope";
isEmptyArray(string); 
console.log("This is not an Array = ", string);


Output:




6. How to find unique values or in an array

The following one-liner removes repeating values from an array, leaving only values that occur just a single time.


const findUniquesInArray = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
 
let arr1 = [1, 2, 3, 4, 5, 1, 2, 3];
console.log(findUniquesInArray(arr1));
 
let arr2 = ['W', 'E', 'L', 'C', 'O', 'M', 'E', 'T', 'O', 'M', 'U', 'O'];
console.log(findUniquesInArray(arr2));
 
let arr3 = [5, 5, 5, 3, 3, 4, 5, 8, 2, 8];
console.log(findUniquesInArray(arr3));

Output:



7. How to generate random hex color

Hex colors are a way of representing colors through hexadecimal values. They follow the format #RRGGBB, where RR is red, GG is green, and BB is blue. The values of hexadecimal colors are in the range from 00 to FF, which specify the intensity of the component. You can generate random hex colors using the following JavaScript code:

const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
console.log(randomHexColor());


Output:



8. How to convert degree to radians and vice versa

Degrees and Radians represent the measure of an angle in geometry. You can easily convert an angle in radians to degrees, and vice-versa, using the following mathematical formulas:


Radians = Degrees × π/180

Degrees = Radians × 180/π


Convert Degrees to Radians

const degreesToRadians = (deg) => (deg * Math.PI) / 180.0;
 
let temp1 = 360;
console.log(degreesToRadians(temp1));
 
let temp2 = 100;
console.log(degreesToRadians(temp2));
 
let temp3 = 90;
console.log(degreesToRadians(temp3));

Output:



Convert Radians to Degrees

const radiansToDegrees = (rad) => (rad * 180) / Math.PI;
 
let temp1 = 1.7453292519943295;
console.log(radiansToDegrees(temp1));
 
let temp2 = 3.141592653589793;
console.log(radiansToDegrees(temp2));
 
let temp3 = 1.5707963267948966;
console.log(radiansToDegrees(temp3));

Output:



9. How to check if code is running in browser

You can check if your code is running in a browser using the following:


const isRunningInBrowser = typeof window === 'object' && typeof document === 'object';
console.log(isRunningInBrowser);


10. How to generate random UUID.

UUID stands for Universally Unique Identifier. It's a 128-bit value used to uniquely identify an object or entity on the internet. Use the following code to generate a random UUID:


const generateRandomUUID = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, generateRandomUUID));
console.log(generateRandomUUID());

Output:



The Tech Platform

0 comments
bottom of page