Skip to content

Instantly share code, notes, and snippets.

@Kingdutch
Last active October 27, 2019 15:25
Show Gist options
  • Select an option

  • Save Kingdutch/96590962ae2c90c8f81fde319bb92dfd to your computer and use it in GitHub Desktop.

Select an option

Save Kingdutch/96590962ae2c90c8f81fde319bb92dfd to your computer and use it in GitHub Desktop.
Code Snippets for Drupaljam:XL 2019 and DrupalCon Amsterdam 2019

Multilingualism makes better programmers

The below Gist contains the code samples that I've used in my talk "Multilingualism makes better programmers".

function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
console.log(name); // use variable declared in the parent function
}
displayName();
}
// Outputs: Mozilla
init();
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
function makeFunc() {
var name = 'Mozilla';
function displayName() {
console.log(name);
}
return displayName;
}
var myFunc = makeFunc();
// Outputs: Mozilla
myFunc();
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
function makeAdder(x) {
return y => x + y;
}
var add6 = makeAdder(6);
var add9 = makeAdder(9);
console.log(add6(9)); // 14
console.log(add9(9)); // 18
function addFunction (x) {
return x + 5;
}
const addArrowFn = x => x + 5;
console.log(addFunction(2)); // 7
console.log(addArrowFn(2)); // 7
enum OptionalInt {
Value(i32),
Missing,
}
let x = OptionalInt::Value(5);
match x {
OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
OptionalInt::Value(..) => println!("Got an int!"),
OptionalInt::Missing => println!("No such luck."),
}
// Source: https://doc.rust-lang.org/1.5.0/book/patterns.html
<?php
/**
* Implements the magic method for getting object properties.
*
* @todo: A lot of code still uses non-fields (e.g. $entity->content in view
* builders) by reference. Clean that up.
*/
public function &__get($name) {
// If this is an entity field, handle it accordingly. We first check whether
// a field object has been already created. If not, we create one.
if (isset($this->fields[$name][$this->activeLangcode])) {
return $this->fields[$name][$this->activeLangcode];
}
// Inline getFieldDefinition() to speed things up.
if (!isset($this->fieldDefinitions)) {
$this->getFieldDefinitions();
}
if (isset($this->fieldDefinitions[$name])) {
$return = $this->getTranslatedField($name, $this->activeLangcode);
return $return;
}
// Else directly read/write plain values. That way, non-field entity
// properties can always be accessed directly.
if (!isset($this->values[$name])) {
$this->values[$name] = NULL;
}
return $this->values[$name];
}
# bad
begin
something_that_might_fail
rescue IOError
# handle IOError
end
begin
something_else_that_might_fail
rescue IOError
# handle IOError
end
# good
def with_io_error_handling
yield
rescue IOError
# handle IOError
end
with_io_error_handling { something_that_might_fail }
with_io_error_handling { something_else_that_might_fail }
import { @set } from "./set.mjs";
import { @tracked } from "./tracked.mjs";
import { @bound } from "./bound.mjs";
import { @defineElement } from "./defineElement.mjs";
@defineElement('counter-widget')
class CounterWidget extends HTMLElement {
@tracked x = 0;
@set onclick = this.clicked;
@bound clicked() { this.x++; }
connectedCallback() { this.render(); }
render() { this.textContent = this.x.toString(); }
}
// Source: https://github.com/tc39/proposal-decorators
DATA SEGMENT
MESSAGE DB "ENTER CHARACTER :$"
X DB ?
ENDS
CODE SEGMENT
ASSUME DS:DATA CS:CODE
START:
MOV AX,DATA
MOV DS,AX
LEA DX,MESSAGE
MOV AH,9
INT 21H
MOV AH,1
INT 21H
MOV X,AL
MOV AH,4CH
INT 21H
ENDS
END START
; Source: http://cssimplified.com/computer-organisation-and-assembly-language-programming/an-assembly-program-to-read-a-character-from-console-and-echo-it
#include <stdio.h>
int main() {
printf("ENTER CHARACTER: ");
char input = getchar();
printf("%s\n", &input);
return 0;
}
#include <iostream>
int main() {
char x;
std::cout << "ENTER CHARACTER: ";
// Technically reads a line.
std::cin >> x;
std::cout << x;
return 0;
}
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Reads an entire line instead of a single character.
rl.question('ENTER CHARACTER: ', char => {
console.log(char);
rl.close();
});
<?php
echo "ENTER CHARACTER: ";
$x = stream_get_contents(STDIN, 1);
echo "$x\n";
import sys
print("ENTER CHARACTER:", end=" ")
sys.stdout.flush()
c = sys.stdin.read(1)
print(c)
// Create an `enum` to classify a web event. Note how both
// names and type information together specify the variant:
// `PageLoad != PageUnload` and `KeyPress(char) != Paste(String)`.
// Each is different and independent.
enum WebEvent {
// An `enum` may either be `unit-like`,
PageLoad,
PageUnload,
// like tuple structs,
KeyPress(char),
Paste(String),
// or like structures.
Click { x: i64, y: i64 },
}
// Source https://doc.rust-lang.org/stable/rust-by-example/custom_types/enum.html
package com.example.examplemod;
import net.minecraft.init.Blocks;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
@Mod(modid = ExampleMod.MODID, version = ExampleMod.VERSION)
public class ExampleMod
{
public static final String MODID = "examplemod";
public static final String VERSION = "1.0";
@EventHandler
public void init(FMLInitializationEvent event)
{
// some example code
System.out.println("DIRT BLOCK >> "+Blocks.dirt.getUnlocalizedName());
}
}
// Source: Minecraft Modding with Forge (Arun Gupta & Aditya Gupta, April 2015, O'Reilly Media, Inc.)
<?php
// As of PHP 7.4.
function createCartExchanger(string $currency, float $rate) {
return fn($item) => [
'label' => $item['label'],
'currency' => $currency,
'price' => $item['price'] * $rate,
];
}
$cartToEuro = createCartExchanger('eur', 0.88);
$cartInEur = array_map($cartToEuro, $cart);
<?php
function createCartExchanger(string $currency, float $rate) {
return function (array $item) use ($currency, $rate) {
return [
'label' => $item['label'],
'currency' => $currency,
'price' => $item['price'] * $rate,
];
};
}
$cartToEuro = createCartExchanger('eur', 0.88);
$cartInEur = array_map($cartToEuro, $cart);
// Exchange rate on 27-06-2019.
const usdToEur = usd => usd * 0.88;
const cart = [
{ label: 'Socks', currency: 'usd', price: 3.99 } ,
{ label: 'Shirt', currency: 'usd', price: 9.99 } ,
{ label: 'Shoes', currency: 'usd', price: 49.99 },
];
for (let i=0; i<cart.length; i++) {
cart[i].price = usdToEur(cart[i].price);
}
// Outputs:
// [ { label: 'Socks', currency: 'eur', price: 3.5112 },
// { label: 'Shirt', currency: 'eur', price: 8.7912 },
// { label: 'Shoes', currency: 'eur', price: 43.9912 } ]
console.dir(cart);
// Exchange rate on 27-06-2019.
const usdToEur = usd => usd * 0.88;
const cart = [
{ label: 'Socks', currency: 'usd', price: 3.99 } ,
{ label: 'Shirt', currency: 'usd', price: 9.99 } ,
{ label: 'Shoes', currency: 'usd', price: 49.99 },
];
const cartInEur = cart.map(item => ({
label: item.label,
currency: 'eur',
price: usdToEur(item.price),
}));
// Outputs:
// [ { label: 'Socks', currency: 'eur', price: 3.5112 },
// { label: 'Shirt', currency: 'eur', price: 8.7912 },
// { label: 'Shoes', currency: 'eur', price: 43.9912 } ]
console.dir(cartInEur);
const cart = [
{ label: 'Socks', currency: 'usd', price: 3.99 } ,
{ label: 'Shirt', currency: 'usd', price: 9.99 } ,
{ label: 'Shoes', currency: 'usd', price: 49.99 },
];
function createCartExchanger(currency, rate) {
return item => ({
label: item.label,
currency: currency,
price: item.price * rate,
});
}
// Exchange rate on 27-06-2019.
const cartToEuro = createCartExchanger('eur', 0.88);
const cartToYen = createCartExchanger('yen', 107.87);
const cartInEur = cart.map(cartToEuro);
const cartInYen = cart.map(cartToYen);
// Outputs:
// [ { label: 'Socks', currency: 'eur', price: 3.5112 },
// { label: 'Shirt', currency: 'eur', price: 8.7912 },
// { label: 'Shoes', currency: 'eur', price: 43.9912 } ]
console.dir(cartInEur);
// Outputs:
// [ { label: 'Socks', currency: 'yen', price: 430.40130000000005 },
// { label: 'Shirt', currency: 'yen', price: 1077.6213 },
// { label: 'Shoes', currency: 'yen', price: 5392.421300000001 } ]
console.dir(cartInYen);
const cart = [
{ label: 'Socks', currency: 'usd', price: 3.99 } ,
{ label: 'Shirt', currency: 'usd', price: 9.99 } ,
{ label: 'Shoes', currency: 'usd', price: 49.99 },
];
const sum = (total, item) => total + item.price;
const cartTotal = cart.reduce(sum, 0);
console.log(cartTotal);
function p(x) { process.stdout.write(x); }
function ret_true() { p("true "); return true; }
function ret_false() { p("false "); return false; }
function nl() { process.stdout.write("\n"); }
ret_true() && p("&& print"); nl();
ret_true() || p("|| print"); nl();
ret_false() && p("&& print"); nl();
ret_false() || p("|| print"); nl();
<?php
function p($x) { echo $x; }
function ret_true() { echo "true "; return true; }
function ret_false() { echo "false "; return false; }
function nl() { echo "\n"; }
ret_true() && p("&& print"); nl();
ret_true() || p("|| print"); nl();
ret_false() && p("&& print"); nl();
ret_false() || p("|| print"); nl();
# good (doesn't work in PHP/JS)
do_something if some_condition
# another good option
some_condition && do_something
<?php
namespace Drupal\image\Plugin\Field\FieldWidget;
/**
* Plugin implementation of the 'image_image' widget.
*
* @FieldWidget(
* id = "image_image",
* label = @Translation("Image"),
* field_types = {
* "image"
* }
* )
*/
class ImageWidget extends FileWidget {
// Body omitted
}
<?php
class Gibberish implements LanguageInterface {
// Required methods omitted for brevity.
public function getDirection() {
return 'outside-in';
}
}
enum LanguageDirection {
LTR,
RTL,
}
trait LanguageInterface {
fn get_direction() -> LanguageDirection;
}
struct Gibberish {}
impl LanguageInterface for Gibberish {
fn get_direction() -> LanguageDirection {
"outside-in"
}
}
match x {
e @ 1 ... 5 => println!("got a range element {}", e),
i => println!("{} was not in our range", i),
}
// Source: https://doc.rust-lang.org/1.5.0/book/patterns.html
<?php
namespace Drupal\Core\Language;
/**
* Defines a language.
*/
interface LanguageInterface {
// [Snip]
/**
* Language written left to right. Possible value of $language->direction.
*/
const DIRECTION_LTR = 'ltr';
/**
* Language written right to left. Possible value of $language->direction.
*/
const DIRECTION_RTL = 'rtl';
// [Snip]
/**
* Gets the text direction (left-to-right or right-to-left).
*
* @return string
* Either self::DIRECTION_LTR or self::DIRECTION_RTL.
*/
public function getDirection();
// [Snip]
}
<?php
/**
* Loads an entity.
*
* @param mixed $id
* The id of the entity to load.
*
* @return static
* The entity object or NULL if there is no entity with the given ID.
*/
// Given we have < 9000 nodes.
// Throws: Error: Call to a member function label() on null
Node::load(9002)->label();
<?php
do_something() and something_else() or try_something_different()
use std::fs::File;
use std::io::prelude::*;
fn main() {
let file = File::open("foo.txt");
match file {
Ok(mut f) => {
let mut contents = String::new();
f.read_to_string(&mut contents).expect("Reading failed");
println!("The contents of the file: {}", contents);
},
Err(_) => println!("Could not open file!")
}
}
use std::fs::File;
use std::io::prelude::*;
fn main() {
let file = File::open("foo.txt");
let mut contents = String::new();
file.read_to_string(&mut contents);
println!("The contents of the file: {}", contents);
}
use std::fs::File;
use std::io::prelude::*;
fn main() {
let file = File::open("foo.txt");
match file {
Ok(mut f) => {
let mut contents = String::new();
f.read_to_string(&mut contents).expect("Reading failed");
}
}
}
enum Result<T, E> {
Ok(T),
Err(E),
}
// Source: https://doc.rust-lang.org/std/result/
const unsorted = [2, 0, 5, 3, 1, 4];
let seen = [0, 0, 0, 0, 0, 0];
// Slice copies the array.
const sorted = unsorted.slice().sort(
(a, b) => {
seen[a]++;
seen[b]++;
return a - b;
}
);
console.log("Number\tTimes seen");
seen.forEach((times, number) => {
console.log(`${number}\t${times}`);
});
// Number Times seen
// 0 3
// 1 3
// 2 5
// 3 4
// 4 3
// 5 4
// slowTransform: wait 1s and return x * 2.
const slowTransform = (x) => {
var waitTill = new Date(new Date().getTime() + 1 * 1000);
while(waitTill > new Date()){}
return x * 2;
}
const unsorted = [2, 0, 5, 3, 1, 4];
// Slice copies the array.
const sorted = unsorted.slice().sort(
(a, b) => {
// Access network, disk, calculate prime number or fibonacci.
return slowTransform(a) - slowTransform(b);
}
);
// [ 0, 1, 2, 3, 4, 5 ]
console.log(sorted);
// Takes about 22 seconds.
const slowTransform = (x) => {
var waitTill = new Date(new Date().getTime() + 1 * 1000);
while(waitTill > new Date()){}
return x * 2;
}
const unsorted = [2, 0, 5, 3, 1, 4];
// Slice copies the array.
const sorted = unsorted.slice()
.map(slowTransform)
.sort(
(a, b) => {
// Access network, disk, calculate prime number or fibonacci.
return a - b;
}
);
// [ 0, 2, 4, 6, 8, 10 ]
console.log(sorted);
// Takes about 6 seconds.
const slowTransform = (x) => {
var waitTill = new Date(new Date().getTime() + 1 * 1000);
while(waitTill > new Date()){}
return x * 2;
}
const unsorted = [2, 0, 5, 3, 1, 4];
// Slice copies the array.
const sorted = unsorted.slice()
.map(x => [x, slowTransform(x)])
.sort(
(a, b) => {
// Access network, disk, calculate prime number or fibonacci.
return a[1] - b[1];
}
)
.map(x => x[0]);
// [ 0, 1, 2, 3, 4, 5 ]
console.log(sorted);
// Takes about 6 seconds.
<?php
function slowTransform($x) {
// Access network, disk, calculate prime number or fibonacci.
sleep(1);
return $x * 2;
}
function sort_return($arr, $callable) {
usort($arr, $callable);
return $arr;
}
$unsorted = [3, 1, 6, 4, 2, 5];
$sorted = array_map(
function ($x) { return $x[0]; },
sort_return(
array_map(
function ($x) {
return [$x, slowTransform($x)];
},
$unsorted
),
function ($a, $b) use (&$seen) {
return $a[1] - $b[1];
}
)
);
// Takes about 6s
<?php
function social_post_form_post_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Show the users picture for new posts.
if ($form_state->getFormObject()->getEntity()->isNew()) {
$user_image = social_post_get_current_user_image();
if ($user_image) {
// Add to a new field, so twig can render it.
$form['current_user_image'] = $user_image;
}
}
// [Snip]
}
<?php
function social_post_form_post_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Show the users picture for new posts.
if ($form_state->getFormObject()->getEntity()->isNew()) {
// Load current user.
$account = User::load(Drupal::currentUser()->id());
// Load compact notification view mode of the attached profile.
if ($account) {
$storage = \Drupal::entityTypeManager()->getStorage('profile');
if (!empty($storage)) {
$user_profile = $storage->loadByUser($account, 'profile');
if ($user_profile) {
$content = \Drupal::entityTypeManager()->getViewBuilder('profile')
->view($user_profile, 'compact_notification');
// Add to a new field, so twig can render it.
$form['current_user_image'] = $content;
}
}
}
}
// [Snip]
}
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
// Source: https://doc.rust-lang.org/1.5.0/book/patterns.html
const x = 3;
switch (x) {
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
case 3:
console.log("three");
break;
default:
console.log("anything");
}
<?php
switch ($x) {
case 1:
echo "one";
break;
case 2:
echo "two";
break;
case 3:
echo "three";
break;
default:
echo "anything";
}
<?php
// Required to actually trigger type errors.
declare(strict_types = 1);
/* An example of PHP 7.4's type hints. */
class TypeHintsExample {
protected string $chant = 'We should come up with a chant!';
public function setChant(string $newChant) {
$this->chant = $newChant;
}
public function chant() {
echo $this->chant . PHP_EOL;
}
public function isAwesome() : bool {
return true;
}
}
$fan = new TypeHintsExample();
$fan->setChant('PHP is improving!');
// Outputs: "PHP is improving!\n"
$fan->chant();
// Throws a TypeError
$fan->setChant(9001);
$fan->chant();
<?php
/* An example of PHP 7.4's type hints. */
class TypeHintsExample {
protected string $chant = 'We should come up with a chant!';
public function setChant(string $newChant) {
$this->chant = $newChant;
}
public function chant() {
echo $this->chant . PHP_EOL;
}
public function isAwesome() : bool {
return true;
}
}
$fan = new TypeHintsExample();
$fan->setChant('PHP is improving!');
// Outputs: "PHP is improving!\n"
$fan->chant();
$fan->setChant(9001);
// Outputs: "9001\n"
$fan->chant();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment