ptrcports/node-print/index.js

120 lines
2.9 KiB
JavaScript

global.stdin = () => {
const fs = require('fs')
const out = fs.readFileSync(0).toString()
return out.tryParseJSON()
}
Object.prototype.map = function(cb) {
return cb(this)
}
String.prototype.lines = function() {
let res = this.split("\n")
return res.at(-1) === '' ? res.slice(0, -1) : res
}
String.prototype.reverse = function() {
return this.split('').reverse().join('')
}
String.prototype.tryParseJSON = function() {
const str = this.trim()
if (
(str.at(0) === '{' && str.at(-1) === '}') ||
(str.at(0) === '[' && str.at(-1) === ']')
) {
try {
return JSON.parse(str)
} catch (err) {
return this.toString()
}
}
return this.toString()
}
Buffer.prototype.tryParseJSON = function() {
const out = this.toString().tryParseJSON()
if (typeof out === 'string') {
return this
} else {
return out
}
}
global.exec = (command, args, options) => {
const child_process = require('child_process')
const res = child_process.spawnSync(command, args, options)
res.stdout = res.stdout?.tryParseJSON()
res.stderr = res.stderr?.tryParseJSON()
return res
}
/* wow it's almost like it's my own package and i can include whatever garbage i want :) */
/* not writing a test for that tho */
global.apkindex = () => stdin()
.split("\n\n")
.filter(str => str.length)
.map(x => Object.fromEntries(x.split("\n").map(e => [e.at(0), e.slice(2)])))
.filter(Boolean)
Array.prototype.sum = function(def = 0) {
return this.reduce((a, b) => a + b, def)
}
Array.prototype.product = function(def = 1) {
return this.reduce((a, b) => a * b, def)
}
Array.prototype.sortNum = function() {
return this.sort((a, b) => a - b)
}
Array.prototype.partition = function(compareFn) {
const a = []
const b = []
this.forEach((elem, i, arr) => {
if (compareFn(elem, i, arr)) {
a.push(elem)
} else {
b.push(elem)
}
})
return [a, b]
}
Array.prototype.chunks = function(chunkSize) {
// inspired by https://stackoverflow.com/questions/8495687/split-array-into-chunks#comment84212474_8495740
return new Array(Math.ceil(this.length / chunkSize))
.fill()
.map((_, i) => this.slice(i * chunkSize, (i + 1) * chunkSize))
}
Set.prototype.union = function(other) {
if (!other || !(other instanceof Set)) throw new TypeError('other must be a Set')
return new Set([...this, ...other])
}
Set.prototype.intersection = function(other) {
if (!other || !(other instanceof Set)) throw new TypeError('other must be a Set')
return new Set([...this].filter(el => other.has(el)))
}
Set.prototype.at = function(index) {
return [...this].at(index)
}
global.matrix = function(x, y, elem) {
return new Array(y).fill().map(() => new Array(x).fill().map((_, i) => {
if (typeof elem === 'function') {
return elem(i)
} else {
return elem
}
}))
}
Number.prototype.toXY = function(width) {
if (!(width && typeof width === 'number')) throw new TypeError('width must be a Number')
return [ this % width, Math.floor(this / width) ]
}