Skip to content

Instantly share code, notes, and snippets.

View ufocoder's full-sized avatar
👽
🛸

Sergey ufocoder

👽
🛸
View GitHub Profile
function closeWithStatus (response, status, headers) {
const data = headers || {};
function end () {
response.writeHead(status, data);
response.end();
}
return end;
}
function closeWithContent (response, status, headers) {
router.get(url, function (req, res) {
function handleSuccess (file) {
res.writeHead(200, { "Content-Type": "application/octet-stream" });
res.write(file);
res.end();
}
function handleError (err) {
res.writeHead(404);
res.end();
}
function runAsPromised (task, ...params) {
return new Promise((resolve, reject) =>
task(...params, higherOrderNodeCallback(resolve, reject))
);
}
runAsPromised(readFile, filePath)
.then(convertToContent)
.then(JSON.stringify)
.then(closeWithContent(res, 200, jsonHeaders))
export const doSomething = higherOrderNodeCallback(doA, doB);
import doSomething from "./do-something";
fstat("./some-file", doSomething);
function passTest () { /* ... */ }
function failTest () { /* ... */ }
const errorCallback = higherOrderNodeCallback(failTest, passTest);
errorCallback(errorObj, null);
const successCallback = higherOrderNodeCallback(passTest, failTest);
successCallback(null, successObj);
readFile(
filePath,
higherOrderNodeCallback(
closeWithContent(res, 200, headers),
closeWithStatus(res, 404)
)
);
let x = 96;
get42(); // 42
get36(); // 36
x = 12;
get18(); // 18
x; // 12
function higherOrderNodeCallback (onSuccess, onError) {
function nodeCallback (err, thingIWant) {
if (err) {
onError(err);
} else {
onSuccess(thingIWant);
}
}
return nodeCallback;
}
function multiply (multiplier) {
return function (x) {
return x * multiplier;
};
}
// ES6:
// const multiply = x => y => x * y;
const triple = multiply(3);
function rememberX (x) {
return function getX () {
return x;
};
}
// В ES6 этот же код может быть представлен так:
// const rememberX = x => () => x;
const get42 = rememberX(42);