Skip to main content

levenshtein distance

Nov 19, 2022CodeCatch
Loading...

More JavaScript Posts

Untitled

Apr 14, 2023Helper

0 likes • 8 views

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]

power set

Nov 19, 2022CodeCatch

0 likes • 2 views

const powerset = arr =>
arr.reduce((a, v) => a.concat(a.map(r => r.concat(v))), [[]]);
powerset([1, 2]); // [[], [1], [2], [1, 2]]

hamming distance

Nov 19, 2022CodeCatch

0 likes • 0 views

const hammingDistance = (num1, num2) =>
((num1 ^ num2).toString(2).match(/1/g) || '').length;
hammingDistance(2, 3); // 1

native data structures

Nov 19, 2022CodeCatch

0 likes • 0 views

const nums = [1, 2, 3];
const strs = Array.from('est');
nums.push(6);
nums.push(4, 9);
strs.unshift('t');
nums.length; // 6
nums[nums.length - 1]; // 9
strs[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); // 25
strs.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; // 5
nums.has(4); // true
nums.delete(4);
nums.has(4); // false
[...nums]; // [1, 2, 3, 5]
nums.clear();
nums.size; // 0
const items = new Map([
[1, { name: 'John' }],
[2, { name: 'Mary' }]
]);
items.set(4, { name: 'Alan' });
items.set(2, { name: 'Jeff' });
items.size; // 3
items.has(4); // true
items.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

Reverse a string

Nov 19, 2022CodeCatch

0 likes • 3 views

const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'

Clone an array

Nov 19, 2022CodeCatch

0 likes • 1 view

// `arr` is an array
const clone = arr => arr.slice(0);
// Or
const clone = arr => [...arr];
// Or
const clone = arr => Array.from(arr);
// Or
const clone = arr => arr.map(x => x);
// Or
const clone = arr => JSON.parse(JSON.stringify(arr));
// Or
const clone = arr => arr.concat([]);