const n = `(function () {
function f1(data, k = 1) {
const centroids = data.slice(0, k);
const distances = Array.from({ length: data.length }, () =>
Array.from({ length: k }, () => 0)
);
const classes = Array.from({ length: data.length }, () => -1);
let itr = true;
while (itr) {
itr = false;
for (let d in data) {
for (let c = 0; c < k; c++) {
distances[d][c] = Math.hypot(
...Object.keys(data[0]).map(key => data[d][key] - centroids[c][key])
);
}
const m = distances[d].indexOf(Math.min(...distances[d]));
if (classes[d] !== m) itr = true;
classes[d] = m;
}
for (let c = 0; c < k; c++) {
centroids[c] = Array.from({ length: data[0].length }, () => 0);
const size = data.reduce((acc, _, d) => {
if (classes[d] === c) {
acc++;
for (let i in data[0]) centroids[c][i] += data[d][i];
}
return acc;
}, 0);
for (let i in data[0]) {
centroids[c][i] = parseFloat(Number(centroids[c][i] / size).toFixed(2));
}
}
}
return classes;
}
function f2(data, labels, point, k = 3) {
const kNearest = data
.map((el, i) => ({
dist: Math.hypot(...Object.keys(el).map(key => point[key] - el[key])),
label: labels[i]
}))
.sort((a, b) => a.dist - b.dist)
.slice(0, k);
return kNearest.reduce(
(acc, { label }, i) => {
acc.classCounts[label] =
Object.keys(acc.classCounts).indexOf(label) !== -1
? acc.classCounts[label] + 1
: 1;
if (acc.classCounts[label] > acc.topClassCount) {
acc.topClassCount = acc.classCounts[label];
acc.topClass = label;
}
return acc;
},
{
classCounts: {},
topClass: kNearest[0].label,
topClassCount: 0
}
).topClass;
}
function f3(str, shift, decrypt = false) {
const s = decrypt ? (26 - shift) % 26 : shift;
const n = s > 0 ? s : 26 + (s % 26);
return [...str]
.map((l, i) => {
const c = str.charCodeAt(i);
if (c >= 65 && c <= 90)
return String.fromCharCode(((c - 65 + n) % 26) + 65);
if (c >= 97 && c <= 122)
return String.fromCharCode(((c - 97 + n) % 26) + 97);
return l;
})
.join('');
}
function f4(arr) {
const a = [...arr];
let l = a.length;
const heapify = (a, i) => {
const left = 2 * i + 1;
const right = 2 * i + 2;
let max = i;
if (left < l && a[left] > a[max]) max = left;
if (right < l && a[right] > a[max]) max = right;
if (max !== i) {
[a[max], a[i]] = [a[i], a[max]];
heapify(a, max);
}
};
for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
for (i = a.length - 1; i > 0; i--) {
[a[0], a[i]] = [a[i], a[0]];
l--;
heapify(a, 0);
}
return a;
}
function f5() {
const bucketSort = (arr, size = 5) => {
const min = Math.min(...arr);
const max = Math.max(...arr);
const buckets = Array.from(
{ length: Math.floor((max - min) / size) + 1 },
() => []
);
arr.forEach(val => {
buckets[Math.floor((val - min) / size)].push(val);
});
return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []);
};
}
function f6() {
const files = ['foo.txt ', '.bar', ' ', 'baz.foo'];
let filePaths = [];
for (let file of files) {
const fileName = file.trim();
if (fileName) {
const filePath = fileName;
filePaths.push(filePath);
}
}
}
function f7() {
const files = ['foo.txt ', '.bar', ' ', 'baz.foo'];
const filePaths = files.reduce((acc, file) => {
const fileName = file.trim();
if (fileName) {
const filePath = fileName;
acc.push(filePath);
}
return acc;
}, []);
}
function f8() {
const files = ['foo.txt ', '.bar', ' ', 'baz.foo'];
const filePaths = files
.map(file => file.trim())
.filter(Boolean)
.map(fileName => fileName);
}
function f9() {
class LinkedList {
constructor(data) {
this.data = data;
}
firstItem() {
return this.data.find(i => i.head);
}
findById(id) {
return this.data.find(i => i.id === id);
}
[Symbol.iterator]() {
let item = { next: this.firstItem().id };
return {
next: () => {
item = this.findById(item.next);
if (item) {
return { value: item.value, done: false };
}
return { value: undefined, done: true };
},
};
}
}
const myList = new LinkedList([
{ id: 'a10', value: 'First', next: 'a13', head: true },
{ id: 'a11', value: 'Last', next: null, head: false },
{ id: 'a12', value: 'Third', next: 'a11', head: false },
{ id: 'a13', value: 'Second', next: 'a12', head: false },
]);
for (let item of myList) {
console.log(item);
}
}
function f10() {
class SpecialList {
constructor(data) {
this.data = data;
}
[Symbol.iterator]() {
return this.data[Symbol.iterator]();
}
values() {
return this.data
.filter(i => i.complete)
.map(i => i.value)
[Symbol.iterator]();
}
}
const myList = new SpecialList([
{ complete: true, value: 'Lorem ipsum' },
{ complete: true, value: 'dolor sit amet' },
{ complete: false },
{ complete: true, value: 'adipiscing elit' },
]);
for (let item of myList) {
console.log(item);
}
for (let item of myList.values()) {
console.log(item);
}
}
function f11() {
const obj = { a: 1, b: 2, c: 3 };
obj[Symbol.iterator] = function* () {
for (let key of Object.keys(obj)) yield { [key]: obj[key] };
};
[...obj];
class IterableNumber extends Number {
*[Symbol.iterator]() {
for (let digit of [...this].map(d => Number.parseInt(d))) yield digit;
}
}
const num = new IterableNumber(1337);
[...num];
}
function f12() {
const formatDuration = ms => {
if (ms < 0) ms = -ms;
const time = {
day: Math.floor(ms / 86400000),
hour: Math.floor(ms / 3600000) % 24,
minute: Math.floor(ms / 60000) % 60,
second: Math.floor(ms / 1000) % 60,
millisecond: Math.floor(ms) % 1000
};
return Object.entries(time)
.filter(val => val[1] !== 0)
.map(([key, val]) => 's')
.join(', ');
};
}
function f13() {
const sleep = (ms) =>
new Promise(resolve => setTimeout(resolve, ms));
const printNums = async () => {
console.log(1);
await sleep(500);
console.log(2);
console.log(3);
};
printNums();
}
function f14() {
const formatSeconds = s => {
const [hour, minute, second, sign] =
s > 0
? [s / 3600, (s / 60) % 60, s % 60, '']
: [-s / 3600, (-s / 60) % 60, -s % 60, '-'];
return (
sign +
[hour, minute, second]
.map(v => Math.floor(v))
.join(':')
);
};
}
function f15() {
const toISOStringWithTimezone = date => {
const tzOffset = -date.getTimezoneOffset();
const diff = tzOffset >= 0 ? '+' : '-';
const pad = n => Math.floor(Math.abs(n));
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
diff + pad(tzOffset / 60) +
':' + pad(tzOffset % 60);
};
}
function f16() {
const countWeekDaysBetween = (startDate, endDate) =>
Array
.from({ length: (endDate - startDate) / (1000 * 3600 * 24) })
.reduce(count => {
if (startDate.getDay() % 6 !== 0) count++;
startDate = new Date(startDate.setDate(startDate.getDate() + 1));
return count;
}, 0);
}
function f17() {
const a = new Date(2022, 1, 10);
const b = new Date(2022, 1, 10);
a.getTime() === b.getTime();
}
function f18() {
const addMinutesToDate = (date, n) => {
const d = new Date(date);
d.setTime(d.getTime() + n * 60000);
return d.toISOString().split('.')[0].replace('T', ' ');
};
}
function f19() {
const formatDuration = ms => {
if (ms < 0) ms = -ms;
const time = {
day: Math.floor(ms / 86400000),
hour: Math.floor(ms / 3600000) % 24,
minute: Math.floor(ms / 60000) % 60,
second: Math.floor(ms / 1000) % 60,
millisecond: Math.floor(ms) % 1000
};
return Object.entries(time)
.filter(val => val[1] !== 0)
.map(([key, val]) => 's')
.join(', ');
};
}
function f20() {
const printNums = () => {
console.log(1);
setTimeout(() => console.log(2), 500);
console.log(3);
};
printNums();
}
function f21() {
const luhnCheck = num => {
const arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
const lastDigit = arr.shift();
let sum = arr.reduce(
(acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val *= 2) > 9 ? val - 9 : val)),
0
);
sum += lastDigit;
return sum % 10 === 0;
};
}
function f22() {
const primes = num => {
let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),
sqroot = Math.floor(Math.sqrt(num)),
numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);
numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x)));
return arr;
};
}
function f23() {
const toFixedWithoutZeros = (num, precision) =>
Number.parseFloat(num.toFixed(precision));
toFixedWithoutZeros(1.001, 2);
toFixedWithoutZeros(1.500, 2);
}
function f24() {
const arithmeticProgression = (n, lim) =>
Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n);
}
function f25() {
class DoublyLinkedList {
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, previous: previousNode };
if (previousNode) previousNode.next = node;
if (nextNode) nextNode.previous = 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] || null;
const nextNode = this.nodes[index + 1] || null;
if (previousNode) previousNode.next = nextNode;
if (nextNode) nextNode.previous = previousNode;
return this.nodes.splice(index, 1);
}
clear() {
this.nodes = [];
}
reverse() {
this.nodes = this.nodes.reduce((acc, { value }) => {
const nextNode = acc[0] || null;
const node = { value, next: nextNode, previous: null };
if (nextNode) nextNode.previous = node;
return [node, ...acc];
}, []);
}
}
}
function f26() {
class Graph {
constructor(directed = true) {
this.directed = directed;
this.nodes = [];
this.edges = new Map();
}
addNode(key, value = key) {
this.nodes.push({ key, value });
}
addEdge(a, b, weight) {
this.edges.set(JSON.stringify([a, b]), { a, b, weight });
if (!this.directed)
this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight });
}
removeNode(key) {
this.nodes = this.nodes.filter(n => n.key !== key);
[...this.edges.values()].forEach(({ a, b }) => {
if (a === key || b === key) this.edges.delete(JSON.stringify([a, b]));
});
}
removeEdge(a, b) {
this.edges.delete(JSON.stringify([a, b]));
if (!this.directed) this.edges.delete(JSON.stringify([b, a]));
}
findNode(key) {
return this.nodes.find(x => x.key === key);
}
hasEdge(a, b) {
return this.edges.has(JSON.stringify([a, b]));
}
setEdgeWeight(a, b, weight) {
this.edges.set(JSON.stringify([a, b]), { a, b, weight });
if (!this.directed)
this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight });
}
getEdgeWeight(a, b) {
return this.edges.get(JSON.stringify([a, b])).weight;
}
adjacent(key) {
return [...this.edges.values()].reduce((acc, { a, b }) => {
if (a === key) acc.push(b);
return acc;
}, []);
}
indegree(key) {
return [...this.edges.values()].reduce((acc, { a, b }) => {
if (b === key) acc++;
return acc;
}, 0);
}
outdegree(key) {
return [...this.edges.values()].reduce((acc, { a, b }) => {
if (a === key) acc++;
return acc;
}, 0);
}
}
}
function f27() {
const toKeyedArray = obj => {
const methods = {
map(target) {
return callback =>
Object.keys(target).map(key => callback(target[key], key, target));
},
reduce(target) {
return (callback, accumulator) =>
Object.keys(target).reduce(
(acc, key) => callback(acc, target[key], key, target),
accumulator
);
},
forEach(target) {
return callback =>
Object.keys(target).forEach(key => callback(target[key], key, target));
},
filter(target) {
return callback =>
Object.keys(target).reduce((acc, key) => {
if (callback(target[key], key, target)) acc[key] = target[key];
return acc;
}, {});
},
slice(target) {
return (start, end) => Object.values(target).slice(start, end);
},
find(target) {
return callback => {
return (Object.entries(target).find(([key, value]) =>
callback(value, key, target)
) || [])[0];
};
},
findKey(target) {
return callback =>
Object.keys(target).find(key => callback(target[key], key, target));
},
includes(target) {
return val => Object.values(target).includes(val);
},
keyOf(target) {
return value =>
Object.keys(target).find(key => target[key] === value) || null;
},
lastKeyOf(target) {
return value =>
Object.keys(target)
.reverse()
.find(key => target[key] === value) || null;
},
};
const methodKeys = Object.keys(methods);
const handler = {
get(target, prop, receiver) {
if (methodKeys.includes(prop)) return methods[prop](...arguments);
const [keys, values] = [Object.keys(target), Object.values(target)];
if (prop === 'length') return keys.length;
if (prop === 'keys') return keys;
if (prop === 'values') return values;
if (prop === Symbol.iterator)
return function* () {
for (value of values) yield value;
return;
};
else return Reflect.get(...arguments);
},
};
return new Proxy(obj, handler);
};
}
function f28() {
const nums = [1, 2, 3];
const strs = Array.from('est');
nums.push(6);
nums.push(4, 9);
strs.unshift('t');
nums.length;
nums[nums.length - 1];
strs[0];
strs[2];
nums.slice(1, 3);
nums.map(n => n * 2);
nums.filter(n => n % 2 === 0);
nums.reduce((a, n) => a + n, 0);
strs.reverse();
strs.join('');
}
function f29() {
class FrequencyMap extends Map {
constructor(iterable) {
super();
iterable.forEach(value => this.add(value));
}
set() {
throw new Error('Please use Map.prototype.add() instead.');
}
add(value) {
if (this.has(value)) super.set(value, this.get(value) + 1);
else super.set(value, 1);
return this;
}
delete(value) {
if (this.get(value) === 1) super.delete(value);
else super.set(value, this.get(value) - 1);
return this;
}
sorted(ascending = true) {
if (ascending) return [...this].sort((a, b) => a[1] - b[1]).map(v => v[0]);
else return [...this].sort((a, b) => b[1] - (1)[1]).map(v => v[0]);
}
}
}
function f30() {
const regexp4 = /^[a-zA-Z0-9-_]+$/;
}
function f31() {
const CSVToJSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf(' ')).split(delimiter);
return data
.slice(data.indexOf(' ') + 1)
.split(' ')
.map(v => {
const values = v.split(delimiter);
return titles.reduce(
(obj, title, index) => ((obj[title] = values[index]), obj),
{}
);
});
};
}
function f32() {
const indexOfSubstrings = function (str, searchValue) {
let i = 0;
while (true) {
const r = str.indexOf(searchValue, i);
}
};
}
function f33() {
const toHSLObject = hslStr => {
const [hue, saturation, lightness] = hslStr.match(/123/g).map(Number);
return { hue, saturation, lightness };
};
}
function f34() {
const isFalsy = value => !value;
const isWhitespaceString = value =>
typeof value === 'string' && /^123*$/.test(value);
const isEmptyCollection = value =>
(Array.isArray(value) || value === Object(value)) &&
!Object.keys(value).length;
const isInvalidDate = value =>
value instanceof Date && Number.isNaN(value.getTime());
const isEmptySet = value => value instanceof Set && value.size === 0;
const isEmptyMap = value => value instanceof Map && value.size === 0;
const isBlank = value => {
if (isFalsy(value)) return true;
if (isWhitespaceString(value)) return true;
if (isEmptyCollection(value)) return true;
if (isInvalidDate(value)) return true;
if (isEmptySet(value)) return true;
if (isEmptyMap(value)) return true;
return false;
};
isBlank(null);
isBlank(undefined);
isBlank(0);
isBlank(false);
isBlank('');
isBlank(' ');
isBlank(NaN);
isBlank([]);
isBlank({});
isBlank(new Date('hello'));
isBlank(new Set());
isBlank(new Map());
}
function f35() {
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
}
return [
'' + f1,
]
})();`
con
console