Skip to main content

array shuffle

Nov 19, 2022CodeCatch
Loading...

More JavaScript Posts

linked list

Nov 19, 2022CodeCatch

0 likes • 1 view

class LinkedList {
constructor() {
this.nodes = [];
}
get size() {
return this.nodes.length;
}
get head() {
return this.size ? this.nodes[0] : null;
}
get tail() {
return this.size ? this.nodes[this.size - 1] : null;
}
insertAt(index, value) {
const previousNode = this.nodes[index - 1] || null;
const nextNode = this.nodes[index] || null;
const node = { value, next: nextNode };
if (previousNode) previousNode.next = node;
this.nodes.splice(index, 0, node);
}
insertFirst(value) {
this.insertAt(0, value);
}
insertLast(value) {
this.insertAt(this.size, value);
}
getAt(index) {
return this.nodes[index];
}
removeAt(index) {
const previousNode = this.nodes[index - 1];
const nextNode = this.nodes[index + 1] || null;
if (previousNode) previousNode.next = nextNode;
return this.nodes.splice(index, 1);
}
clear() {
this.nodes = [];
}
reverse() {
this.nodes = this.nodes.reduce(
(acc, { value }) => [{ value, next: acc[0] || null }, ...acc],
[]
);
}
*[Symbol.iterator]() {
yield* this.nodes;
}
}
const list = new LinkedList();
list.insertFirst(1);
list.insertFirst(2);
list.insertFirst(3);
list.insertLast(4);
list.insertAt(3, 5);
list.size; // 5
list.head.value; // 3
list.head.next.value; // 2
list.tail.value; // 4
[...list.map(e => e.value)]; // [3, 2, 1, 5, 4]
list.removeAt(1); // 2
list.getAt(1).value; // 1
list.head.next.value; // 1
[...list.map(e => e.value)]; // [3, 1, 5, 4]
list.reverse();
[...list.map(e => e.value)]; // [4, 5, 1, 3]
list.clear();
list.size; // 0

Convert data to yyyy mm dd format

Nov 19, 2022CodeCatch

0 likes • 1 view

// `date` is a `Date` object
const formatYmd = date => date.toISOString().slice(0, 10);
// Example
formatYmd(new Date()); // 2020-05-06

Truncate to fixed decimal

Nov 19, 2022CodeCatch

0 likes • 0 views

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1); // 25.1
toFixed(25.198726354, 2); // 25.19
toFixed(25.198726354, 3); // 25.198
toFixed(25.198726354, 4); // 25.1987
toFixed(25.198726354, 5); // 25.19872
toFixed(25.198726354, 6); // 25.198726

insertion sort

Nov 19, 2022CodeCatch

0 likes • 0 views

const insertionSort = arr =>
arr.reduce((acc, x) => {
if (!acc.length) return [x];
acc.some((y, j) => {
if (x <= y) {
acc.splice(j, 0, x);
return true;
}
if (x > y && j === acc.length - 1) {
acc.splice(j + 1, 0, x);
return true;
}
return false;
});
return acc;
}, []);
insertionSort([6, 3, 4, 1]); // [1, 3, 4, 6]

Get timezone as a string

Nov 19, 2022CodeCatch

0 likes • 0 views

const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
// Example
getTimezone();

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]]