Loading...
More JavaScript Posts
const quickSort = arr => {const a = [...arr];if (a.length < 2) return a;const pivotIndex = Math.floor(arr.length / 2);const pivot = a[pivotIndex];const [lo, hi] = a.reduce((acc, val, i) => {if (val < pivot || (val === pivot && i != pivotIndex)) {acc[0].push(val);} else if (val > pivot) {acc[1].push(val);}return acc;},[[], []]);return [...quickSort(lo), pivot, ...quickSort(hi)];};console.log(quickSort([1, 6, 1, 5, 3, 2, 1, 4])) // [1, 1, 1, 2, 3, 4, 5, 6]
const powerset = arr =>arr.reduce((a, v) => a.concat(a.map(r => r.concat(v))), [[]]);powerset([1, 2]); // [[], [1], [2], [1, 2]]
const hammingDistance = (num1, num2) =>((num1 ^ num2).toString(2).match(/1/g) || '').length;hammingDistance(2, 3); // 1
const nums = [1, 2, 3];const strs = Array.from('est');nums.push(6);nums.push(4, 9);strs.unshift('t');nums.length; // 6nums[nums.length - 1]; // 9strs[0]; // 't'strs[2]; // 's'nums.slice(1, 3); // [2, 3]nums.map(n => n * 2); // [2, 4, 6, 12, 8, 18]nums.filter(n => n % 2 === 0); // [2, 6, 4]nums.reduce((a, n) => a + n, 0); // 25strs.reverse(); // ['t', 's', 'e', 't']strs.join(''); // 'test'const nums = new Set([1, 2, 3]);nums.add(4);nums.add(1);nums.add(5);nums.add(4);nums.size; // 5nums.has(4); // truenums.delete(4);nums.has(4); // false[...nums]; // [1, 2, 3, 5]nums.clear();nums.size; // 0const items = new Map([[1, { name: 'John' }],[2, { name: 'Mary' }]]);items.set(4, { name: 'Alan' });items.set(2, { name: 'Jeff' });items.size; // 3items.has(4); // trueitems.get(2); // { name: 'Jeff' }items.delete(2);items.size; // 2[...items.keys()]; // [1, 4][...items.values()]; // [{ name: 'John' }, { name: 'Alan' }]items.clear();items.size; // 0
const reverse = str => str.split('').reverse().join('');reverse('hello world');// Result: 'dlrow olleh'
// `arr` is an arrayconst clone = arr => arr.slice(0);// Orconst clone = arr => [...arr];// Orconst clone = arr => Array.from(arr);// Orconst clone = arr => arr.map(x => x);// Orconst clone = arr => JSON.parse(JSON.stringify(arr));// Orconst clone = arr => arr.concat([]);