Some coding tricks I found at work


function removeFirstTwo(list){

const [,,...arr] = list

return arr

}


Swap 2 numbers without temp variable

int x = 10, y = 5;

x = x + y;

y = x - y;

x = x - y;


Download file in UI by creating a temp link

downloadPDF = (pdfLink, pdfName) => {
axios({
url: pdfLink,
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', pdfName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});

}; 


Sometimes useful for StringBuilder

String SEPARATOR = "";

for(int i = 0; i < arr.length; i++){

    sb.append(SEPARATOR);

    sb.append(arr[i]);

    SEPARATOR=",";

}


Autowired in static


@Component

public class StaticLogger{

    private static Dao dao;

    @Autowired

    private Dao dao1;

    @PostConstruct

    private void initStaticDao(){

        dao = this.dao1;

    }

}


Destructure is good, but better with default value, const {a, b, c} = obj || {}


Better if statement check

const condition = [1,2,3,4]

if(condition.includes(type)){...}

if(value??'' !==''){...}


Get flaten array from object, Object.values(deps).flat(Infinity)



Comments