Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save paulknulst/cc523141e4ce39f04815df3f933efc5d to your computer and use it in GitHub Desktop.
Save paulknulst/cc523141e4ce39f04815df3f933efc5d to your computer and use it in GitHub Desktop.
12 Important JavaScript Functions To Improve Code as a Web Developer on Medium: https://medium.com/@paulknulst
// 1. Valid Json
const isValidJSON = (str) => {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
isValidJSON('{"firstname":"Paul","surname":"Knulst"}'); // true
isValidJSON('{"firstname":"Paul",surname:"Knulst"}'); // false
isValidJSON(null); // true
// 2. Days Between Two Dates
const daysBetween = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);
daysBetween(new Date('2022-11-12'), new Date('2023-01-11'));
// 3. Check For Palindrome
const isPalindrome = (str) => str === str.split('').reverse().join('');
isPalindrome('rotator'); // true
isPalindrome('kayak'); // true
isPalindrome('twitter'); // false
isPalindrome('radar'); // true
isPalindrome('challenge'); // false
// 4. Calculate Factorial
const factorial = (number) =>
number <= 0
? (() => {
throw new TypeError('not possible');
})()
: number <= 1
? 1
: number * factorial(number - 1);
factorial(-4); // Error not possible
factorial(5); // 120
factorial(9); // 362880
// 5. Check if number is Power of Two
const isNumberPowerOfTwo = (number) => !!number && (number & (number - 1)) === 0;
isNumberPowerOfTwo(100); // false
isNumberPowerOfTwo(128); // false
// 6. Convert any number to digit
const convertNrToDigitArray = (number) =>
[...`${number}`].map((el) => parseInt(el));
convertNrToDigitArray(1234); // [1, 2, 3, 4]
convertNrToDigitArray(23658126); // [2, 3, 6, 5, 8, 1, 2, 6]
// 7. Calculate Sum of two or more values
const sumOfNumbers = (...arr) => [...arr].reduce((acc, currentValue) => acc + currentValue, 0);
sumOfNumbers(5, 6, 4, 3, 2); // 20
sumOfNumbers(...[1, 4, 5, 3, 6, 7]); // 26
// 8. Stringify every object
const stringify = (obj) => {
for (let [key, value] of Object.entries(obj)) {
console.log(`${key}: ${value}`);
}
};
const obj = {
firstname: 'Paul',
surname: 'Knulst',
medium: 'paulknulst',
homepage: 'https://www.paulsblog.dev',
};
stringify(obj);
// will produce:
// firstname: Paul
// surname: Knulst
// twitter: paulknulst
// homepage: https://www.knulst.dev
// 9. Count elements with reduce function
const names = ['Paul', 'John', 'Paul', 'Steve', 'Harald', 'John', 'Paul'];
const countNames = names.reduce((names, name) => {
names[name] = (names[name] || 0) + 1;
return names;
}, {});
console.log(countNames); // {Paul: 3, John: 2, Steve: 1, Harald: 1}
// 10. Measure function time in milliseconds
const startTime = performance.now();
doHeavyFunction();
const endTime = performance.now();
console.log(
'doHeavyFunction took ' +
(endTime - startTime) +
' milliseconds to execute.'
);
// 11. Cherry-pick keys while using JSON.stringify
const user = {
id: 1337,
name: 'Paul Knulst',
role: 'Senior Engineer',
company: 'Realcore',
page: 'https://www.paulsblog.dev',
github: 'https://www.github.com/paulknulst',
};
JSON.stringify(user, ['name', 'role', 'page']);
// returns
// {
// "name": "Paul Knulst",
// "role": "Senior Engineer",
// "page": "https://www.paulsblog.dev"
// }
// 12. Replacer function to limit output
function replacer(key, value) {
if (typeof value === 'string' && key !== 'name' && key !== 'page') {
return undefined;
}
return value;
}
const userObject = {
id: 1337,
name: 'Paul Knulst',
role: 'Senior Engineer',
company: 'Realcore',
page: 'https://www.paulsblog.dev',
github: 'https://www.github.com/paulknulst',
};
JSON.stringify(userObject, replacer);
// returns
// {
// "id": 1337
// "name": "Paul Knulst",
// "page": "https://www.paulsblog.dev"
// }
// BONUS: Calculate Execution of any JavaScript function
let count = 0;
console.time('total');
console.time('sub1');
for (let i = 0; i < 10000000; i++) {
count++;
}
console.timeEnd('sub1');
console.time('sub2');
for (let i = 0; i < 10000000; i++) {
count++;
}
console.timeEnd('sub2');
console.time('sub3');
for (let i = 0; i < 10000000; i++) {
count++;
}
console.timeEnd('sub3');
console.timeEnd('total');
// will log:
// sub1: 19.036865234375 ms
// sub2: 19.491943359375 ms
// sub3: 18.36572265625 ms
// total: 57.1337890625 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment