/ Gists / JS oneliners

Gists - JS oneliners

On gists

prevAll, nextAll in pure jS (jQuery replacement)

JavaScript JS oneliners ES 6

index.html #

  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li id="selected">6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
  </ul>

On gists

Debounce, Throttle, Wait (ES6 Utils)

JS oneliners

fns.js #

export function debounce(fn, wait){
    let timer;
   return function(...args){
     if(timer) {
        clearTimeout(timer); // clear any pre-existing timer
     }
     const context = this; // get the current context
     timer = setTimeout(()=>{
        fn.apply(context, args); // call the function if time expires
     }, wait);
   }
}


export function throttle(fn, wait){
    let throttled = false;
    return function(...args){
        if(!throttled){
            fn.apply(this,args);
            throttled = true;
            setTimeout(()=>{
                throttled = false;
            }, wait);
        }
    }
}


export function wait(waitTime, callback = () => {}) {
  return new Promise(resolve => {
    setTimeout(() => {
      callback()
      resolve(true)
    }, waitTime)
  })
}



window.addEventListener('resize', debounce(() => {
    console.log('Resized!');
}, 200));


window.addEventListener('scroll', throttle(() => {
    console.log('Scrolled!');
}, 200));

On gists

Fast fill array

JavaScript JS oneliners

fast-fill.js #

const newData = Array(20)
      .fill(0)
      .map((_, index) =>  index++);

On gists

Detect device type

JavaScript JS oneliners

snippet.js #

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ?  Mobile 
    :  Desktop ;
console.log(detectDeviceType());

On gists

Check if the array contains a value / get index

JavaScript JS oneliners

ex.js #

const array = [ 'fatfish', 'hello', 'world', 24 ]
console.log(array.indexOf('fatfish')) // 0
console.log(array.indexOf('medium')) // -1



const array = [
  {
    name: 'fatfish'
  },
  {
    name: 'hello'
  },
  {
    name: 'world'
  },
]
const index = array.findIndex((it) => it.name === 'fatfish') // 0

On gists

Flatten multi-layer arrays

JavaScript JS oneliners

solution1.js #

const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
const flattenArray = (array) => {
  return array.reduce((res, it) => {
    return res.concat(Array.isArray(it) ? flattenArray(it) : it)
  }, [])
}
console.log(flattenArray(array)) // [1, 2, 3, 4, 5]

On gists

Shuffle the values of an array randomly

JavaScript JS oneliners

ex.js #

const prizes = [ 'A', 'B', 'C', 'D' ]
prizes.sort(() => 0.5 - Math.random())

On gists

Objects

JS oneliners

demo.js #

// https://blog.bitsrc.io/common-js-development-skills-5053f0a74ced

// Clone object
const _obj = { a: 0, b: 1, c: 2 };
const obj = { ..._obj };
const obj = JSON.parse(JSON.stringify(_obj));
// obj => { a: 0, b: 1, c: 2 }


// Merge objects
const obj1 = { a: 0, b: 1, c: 2 };
const obj2 = { c: 3, d: 4, e: 5 };
const obj = { ...obj1, ...obj2 };
// obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }

On gists

Arrays

JS oneliners

demo.js #

// Clone array
const _arr = [0, 1, 2];
const arr = [..._arr];
// arr => [0, 1, 2]


// Merge array
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const arr = [...arr1, ...arr2];
// arr => [0, 1, 2, 3, 4, 5];


// Deduplicated array
const arr = [...new Set([0, 1, 1, null, null])];
// arr => [0, 1, null]


// Obfuscated / randomize array
const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);
// arr => [3, 4, 0, 5, 1, 2]


// Empty array
const arr = [0, 1, 2];
arr.length = 0;
// arr => []


// Insert member at the beginning of the array
let arr = [1, 2];
arr.unshift(0);
arr = [0].concat(arr);
arr = [0, ...arr];
// arr => [0, 1, 2]


// Insert members at the end of the array
let arr = [0, 1]; 
arr.push(2);
arr.concat(2);
arr[arr.length] = 2;
arr = [...arr, 2];
// arr => [0, 1, 2]


// Count number of array members
const arr = [0, 1, 1, 2, 2, 2];
const count = arr.reduce((t, v) => {
 t[v] = t[v] ? ++t[v] : 1;
 return t;
}, {});
// count => { 0: 1, 1: 2, 2: 3 }


// Get random array member
const arr = [0, 1, 2, 3, 4, 5];
const randomItem = arr[Math.floor(Math.random() * arr.length)];
// randomItem => 1


// Create an array of specified length
const arr = [...new Array(3).keys()];
// arr => [0, 1, 2]

const arr = new Array(3).fill(0);
// arr => [0, 0, 0]

On gists

Generate range random numbers

JS oneliners

demo.js #

const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const num = RandomNum(1, 10); // 5