Skip to content

Instantly share code, notes, and snippets.

@RayyanNafees
Last active August 14, 2020 08:58
Show Gist options
  • Save RayyanNafees/f9e33b87d738890e2c2f3137e363749b to your computer and use it in GitHub Desktop.
Save RayyanNafees/f9e33b87d738890e2c2f3137e363749b to your computer and use it in GitHub Desktop.
export const ord = num => String.fromCharCode(num);
export const chr = char => char.charCodeAt(0);
export const all = (...conditions) => conditions.length > 1 ? !(conditions.map(i => Boolean(i)).includes(false)) : all(...conditions[0]);
export const any = (...conditions) => conditions.length > 1 ? conditions.map(i => Boolean(i)).includes(true) : all(...conditions[0]);
export const bool = obj => !!obj;
export const exec = cmd => (new Function(cmd))(); // Can be blocked by some browsers... because of security issues
export const type = obj => { typestr = typeof(obj); return eval(typestr[0].toUpperCase() + typestr.slice(1)); };
function isiterable(struct) {
try {
for (let i of struct);
return true;
} catch (TypeError) {
return false;
}
}
export const len = function(collection) {
if (isiterable(collection)) {
let ln = collection.length;
if (!ln) {
let count = 0;
for (let i of collection) count++;
return count;
}
}
let count = 0;
for (let i in collection)
count++;
return count;
};
export const range = function(stop$start, stop = null, step = 1) {
let arr = [];
for (let i = !stop ? 0 : stop$start; i < (!stop ? stop$start : stop); arr.push(i), i += step);
return arr;
};
export const dir = function(obj) {
//* pass as type(obj) to get its attributes
let arr = [];
for (let i in obj)
arr.push(i);
if (arr.length)
return arr;
};
export const map = (func, iterable) => [...iterable].map(func);
export const filter = (func, iterable) => [...iterable].filter(func);
// Error Prones____________________________________
export const max = function(...iterables) {
if (iterables.length === 1)
return max(...iterables[0]);
let elem = (iterables[0]);
if (type(elem) === Number)
return Math.max(...iterables);
else if (isiterable(elem) && len(elem) > -1)
return Math.max(...map(i => len(i), iterables));
};
export const min = function(...iterables) {
let arr = [...iterables];
for (let i = 1; i < iterables.length; i++)
arr.splice(arr.indexOf(max(...iterables)));
return [arr, arr[0]];
};
//____________________________________________________
export const zip = function*(...iterables) {
if (iterables.length === 1) {
for (let i of iterables[0]) yield i;
}
let smallest_len = Math.min(...map(i => len(i), iterables));
let iter_items = [];
for (let i in iterables)
iterables[i] = [...iterables[i]]; //Make every iterable an array
for (let i = 0; i < smallest_len; i++) {
for (let iterable of iterables)
iter_items.push(iterable[i]);
yield iter_items;
iter_items = [];
}
};
export const enumerate = iterable => zip(range(iterable.length), iterable);
export const reversed = iterable => zip([...iterable].reverse());
export const sum = function(iterable) {
let n = 0;
for (let i of iterable)
n += i;
return n;
};
export const abs = n => Math.abs(n);
export const print = function(...vals) {
//* Keyword stuff!
let sep = ' ';
let end = '\n';
let file = console;
let last = vals[vals.length - 1];
if (
typeof(last) === 'object' &&
len(last) <= 3 &&
any(['sep', 'end', 'file'].map((i) => i in last))
) {
let props = vals[vals.length - 1];
sep = props.sep || ' ';
end = props.end || '\n';
file = props.file || console;
vals.pop();
}
//* Stringification
for (let i in range(len(vals))) {
try {
vals[i] = vals[i].__repr__();
} catch (TypeError) {
let strobj = JSON.stringify(vals[i]);
vals[i] = len(strobj) > 2 ? strobj : JSON.constructor(vals[i]);
}
}
let str = [...vals].join(sep) + end;
return dir(file).includes('log') ? file.log(str) : file.write(str);
};
//* Built-in Data Structs_____________________
export class list extends Array {
constructor(iterable) {
super(...iterable);
this.arr = iterable ? [...iterable] : [];
this.length = this.arr.length;
}
__repr__() { return JSON.stringify(this.arr); }
count(obj) {
let occurance = 0;
for (let i of this.arr)
obj === i ? occurance++ : null;
return occurance;
}
clear() { this.arr = []; }
copy() { return this.arr.copyWithin(); }
append(obj) { this.arr.push(obj); }
extend(new_arr) { this.arr = [...this.arr, ...new_arr]; }
insert(index, obj) { this.arr.splice(index, 0, obj); }
pop(index = 0) { return this.arr.splice(index, 1)[0]; }
remove(obj) { this.pop(this.arr.indexOf(obj)); }
index(obj) { return this.arr.indexOf(obj); }
reverse() { return this.arr.reverse(); }
sort() { this.arr.sort(); }
}
export class dict extends Object, Map {
construct(iterable) {
super(iterable);
this.obj = {};
for (let [k, v] in zip(Object.keys(iterable), Object.values(iterable)))
this.obj[k] = v;
}
items() {
let arr = [];
for (let [k, v] in zip(this.keys(), this.values()))
arr.push([k, v]);
return arr;
}
pop() {}
popitem() {}
setdefault() {}
update() {}
copy() {}
fromkeys() {}
get(val, alter) { return (this.obj[val] || alter); }
clear() { this.obj = {}; }
keys() { return Object.keys(this.obj); }
values() { return Object.values(this.obj); }
__repr__() { return JSON.stringify(this.obj); }
__str__() { return this.__repr__(); }
}
export class set extends Set {
construct(iterable) { super(iterable); }
__repr__() {}
__str__() {}
add() {}
clear() {}
copy() {}
difference() {}
difference_update() {}
discard() {}
intersection() {}
intersection_update() {}
isdisjoint() {}
issubset() {}
issuperset() {}
pop() {}
remove() {}
symmetric_difference() {}
symmetric_difference_update() {}
union() {}
update() {}
}
export class int extends Number {
construct(iterable) { super(iterable); }
__repr__() {}
__str__() {}
as_integer_ratio() {}
bit_length() {}
conjugate() {}
denominator() {}
from_bytes() {}
imag() {}
numerator() {}
real() {}
to_bytes() {}
}
export class float extends Number {
construct(iterable) { super(iterable); }
__repr__() {}
__str__() {}
as_integer_ratio() {}
conjugate() {}
fromhex() {}
hex() {}
imag() {}
is_integer() {}
real() {}
}
export class str extends String {
construct(obj) {
super(obj);
let func = obj.__str__ || JSON.stringify;
this.strs = (x = func(obj)).length > 2 ? x : String(obj);
}
startswith(chars) { return super.startsWith(chars); }
endswith(chars) { return super.endsWith(chars); }
join(arr) { return arr.join(this.strs); }
//* Yet to work on__________________
__repr__() { return super(obj); }
strip() { return super.trim(); }
lstrip() { return super.trimLeft(); }
rstrip() { return super.trimRight(); }
format() {}
capitalize() { return this.strs[0].toUppercase() + this.strs.slice(1).toLowerCase(); }
title() { return this.capitalize(); }
lower() { return super.toLowerCase(); }
upper() { return super.toUpperCase(); }
casefold() {}
center() {}
count() {}
encode() {}
expandtabs() {}
find() {}
format_map() {}
index() {}
isalpha() {}
isascii() {}
isdecimal() {}
isdigit() {}
isidentifier() {}
islower() {}
isnumeric() {}
isprintable() {}
isalnum() {
let s = this.strs;
return all(s.isalpha(), s.isdecimal(), s.isdigit(), s.isnumeric());
}
isspace() {
let sp = char => this.strs.includes(char);
return any(sp('\n'), sp('\t'), sp(' '));
}
istitle() {}
isupper() {}
ljust() {}
maketrans() {}
partition() {}
replace() {}
rfind() {}
rindex() {}
rjust() {}
rpartition() {}
rsplit() {}
split() {}
splitlines() {}
swapcase() {}
translate() {}
zfill() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment