Skip to content

Instantly share code, notes, and snippets.

View lukehorvat's full-sized avatar

Luke Horvat lukehorvat

View GitHub Profile
@lukehorvat
lukehorvat / express-curl-middleware.js
Created August 27, 2015 12:45
Express middleware to log a JSON request as a cURL command. Inspired by Chrome's "Copy as cURL" feature.
// After body-parsing middleware...
app.use(function(req, res, next) {
console.log(
"curl '%s://%s%s' -X %s -H 'Content-Type: %s' -d '%s'",
req.protocol,
req.get("host"),
req.originalUrl,
req.method,
req.get("Content-Type"),
JSON.stringify(req.body)
@lukehorvat
lukehorvat / mapped-type-conversion.ts
Last active June 6, 2020 14:12
Convert one mapped type to another. (TypeScript)
type Input<Output> = {
[K in keyof Output]: { foo: () => Output[K] };
};
function convert<Output>(input: Input<Output>): Output {
const keys = Object.keys(input) as (keyof Input<Output>)[];
return keys.reduce(
(output, key) => ({ ...output, [key]: input[key].foo() }),
{} as Output
@lukehorvat
lukehorvat / NumberPickerDialogPreference.java
Last active June 17, 2021 14:06
An Android preference class that provides a user with the means to select an integer from a NumberPicker and persist it. (License: MIT License)
package com.lukehorvat;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.NumberPicker;
@lukehorvat
lukehorvat / gulpfile.js
Last active March 3, 2023 18:17
A small example of a "Vinyl adapter" that replaces `gulp.src`. Demonstrates how to create a stream for a "fake" (in-memory only) file.
import gulp from 'gulp';
import Vinyl from 'vinyl';
import vinylAdapter from './vinyl-adapter';
gulp.task('build', () => {
const file = new Vinyl({
path: 'hello.js',
contents: Buffer.from(`console.log('👋');`)
});
@lukehorvat
lukehorvat / gulpfile.js
Created March 3, 2023 20:43
An example of how to print out the names of files streamed by gulp. Sometimes useful for debugging purposes.
import gulp from 'gulp';
import { Transform } from 'node:stream';
gulp.task('build', () => {
return gulp
.src('src/**/*.js')
.pipe(
new Transform({
objectMode: true,
transform(file, encoding, callback) {
@lukehorvat
lukehorvat / es6-map-to-object-literal.js
Last active January 8, 2024 10:32
Convert ES6 Map to Object Literal
let map = new Map();
map.set("a", 1);
map.set("b", 2);
map.set("c", 3);
let obj = Array.from(map).reduce((obj, [key, value]) => (
Object.assign(obj, { [key]: value }) // Be careful! Maps can have non-String keys; object literals can't.
), {});
console.log(obj); // => { a: 1, b: 2, c: 3 }