Skip to content

Instantly share code, notes, and snippets.

// console.log(solveRPN('5 3 6 * + 5 3 / - 7 +')); // becomes `28.333333333333332`
function solveRPN(input) {
const stack = [];
const items = input.trim().split(' ');
for (const item of items) {
if (!isNaN(item) && isFinite(item)) {
stack.push(parseFloat(item));
} else {
const [a, b] = [stack.pop(), stack.pop()];
@devsnek
devsnek / comments.md
Last active July 8, 2017 12:18
mathematical expression parser, 100 lines

This is a parser/lexer for mathematical expressions.

It all starts with the parse/1 function, which begins by building an array (in a rather ineffecient way) from the iterator returned by lex/2. The lexer is the part of this I had the most fun with.

It basically brute-forces the beginning of the string with regex until something matches up, at which point it removes that match from the string and yields the token.

const Module = require('module');
require.fromString = (str, filename = '') => {
const m = new Module(filename, module.parent);
if (typeof __dirname !== 'undefined') m.paths = Module._nodeModulePaths(__dirname);
m._compile(str, filename);
return m.exports;
}
@devsnek
devsnek / example.js
Last active July 17, 2017 20:05
actual proper js semaphore smh
const sharedBuffer = new SharedArrayBuffer(2 * Int32Array.BYTES_PER_ELEMENT);
const sharedArray = new Int32Array(sharedBuffer);
// new semaphore with max of 10
const s = Semaphore.create(sharedArray, 0, 10);
s.acquire(11) // false
s.acquire(10) // true
s.acquire() // false
s.release(5) // true
const l = require('fast-levenshtein');
const has = (o, p) => Object.prototype.hasOwnProperty.call(o, p);
function leven(target, list) {
const sorted = [];
for (const item of list) {
const score = l.get(target, item);
sorted.splice(+score - 1, 0, item);
}
let ret;
function unindent(str, ...keys) {
if (Array.isArray(str)) {
const copy = [];
for (const i in keys) {
copy.push(str[i]);
copy.push(keys[i]);
}
str = copy.join('');
}
const lines = str.split('\n').filter((l) => l);
const Module = require('module');
const fs = require('fs');
const path = require('path');
const util = require('util');
const writeFileAsync = util.promisify(fs.writeFile.bind(fs));
const CACHE_NAME = 'package-cache.json';
const defaultResolveFilename = Module._resolveFilename.bind(Module);
const cwd = process.cwd();
#include <iostream>
#include <sys/stat.h>
#include <string>
using namespace std;
class Node {
private:
int value;
Node* next;
const kMap = Symbol('map');
class EventEmitter {
constructor() {
this[kMap] = new Map();
}
on(event, handler, once = false) {
const fn = ({ detail }) => handler.apply(this, detail);
this[kMap].set(handler, { fn, once });
return window.addEventListener(event, fn, { once });
}