Fixes, plus function related code

This commit is contained in:
fkereki
2018-03-29 14:47:23 -03:00
parent 72034b13e4
commit b30b89aa78
4 changed files with 73 additions and 6 deletions
+39
View File
@@ -0,0 +1,39 @@
/* @flow */
function root(a: number, n: number = 2): number {
return a ** (1 / n);
}
console.log(root(125, 3)); // 5
console.log(root(4)); // 2
console.log(root(9, undefined)); // 3
const nthRoot = (a: number, n: number = 2): number => a ** (1 / n);
console.log(nthRoot(64)); // 8
class Counter {
count: number; // required by Flow
constructor(i: number = 0) {
this.count = i;
}
inc(n: number = 1) {
this.count += n;
}
}
const cnt = new Counter();
cnt.inc(3);
cnt.inc();
cnt.inc();
console.log(cnt.count); // 5
function nonsense(a = 2, b = a + 1, c = a * b, d = 9) {
console.log(a, b, c, d);
}
nonsense(1, 2, 3, 4); // 1 2 3 4
nonsense(); // 2 3 6 9
nonsense(undefined, 4, undefined, 6); // 2 4 8 6
+28
View File
@@ -0,0 +1,28 @@
/* @flow */
type genericFunction = (...args: Array<mixed>) => mixed;
type higherOrderFunction = genericFunction => genericFunction;
const once: higherOrderFunction = (fn: genericFunction) => {
let done = false;
return (...args) => {
if (!done) {
done = true;
fn(...args);
}
};
};
const sayHello = () => {
console.log("Hello!");
};
sayHello(); // Hello!
sayHello(); // Hello!
sayHello(); // Hello!
const sayHelloOnce = once(sayHello);
sayHelloOnce(); // Hello!
sayHelloOnce(); // (no output)
sayHelloOnce(); // (no output)
@@ -14,7 +14,7 @@ async function getMontevideo() {
try {
const montevideoData = await get_weather(MONTEVIDEO_UY);
console.log("Montevideo, with promises");
console.log("Montevideo, with async/await");
console.log(`Montevideo: ${montevideoData.data.length} bytes`);
} catch (error) {
console.log(error.message);
+5 -5
View File
@@ -7,14 +7,14 @@ const KILOMETERS_PER_MILE = 1.60934;
const GRAMS_PER_POUND = 453.592;
const GRAMS_PER_OUNCE = 28.3495;
const milesToKm: conversion = m => m / KILOMETERS_PER_MILE;
const kmToMiles: conversion = k => k * KILOMETERS_PER_MILE;
const milesToKm: conversion = m => m * KILOMETERS_PER_MILE;
const kmToMiles: conversion = k => k / KILOMETERS_PER_MILE;
const poundsToKg: conversion = p => p / (GRAMS_PER_POUND / 1000);
const kgToPounds: conversion = k => k * GRAMS_PER_POUND / 1000;
const poundsToKg: conversion = p => p * (GRAMS_PER_POUND / 1000);
const kgToPounds: conversion = k => k / (GRAMS_PER_POUND / 1000);
const gramsToOunces: conversion = g => g / GRAMS_PER_OUNCE;
const ouncesToGrams: conversion = o => o * GRAMS_PER_OUNCE;
const gramsToOunces: conversion = g => g / GRAMS_PER_OUNCE;
/*
It's usually preferred to include all "export"