Skip to content

Instantly share code, notes, and snippets.

View straybro's full-sized avatar
🐢
418 I'm a teapot

straybro straybro

🐢
418 I'm a teapot
View GitHub Profile
function ustr($str){
$arr = explode(' ', $str);
return implode(array_map(function($word) {
$word[0] = mb_strtoupper($word[0], 'utf-8');
return $word;
}, $arr), ' ');
}
@straybro
straybro / upc.php
Created May 12, 2020 21:51 — forked from tuscen/upc.php
<?php
$sentence = "Пусть этой строкой будет вот прямо эта строка.";
function solution($string) {
$ucfirst = function($word) {
$firstChar = mb_substr($word, 0, 1, 'utf8');
$rest = mb_substr($word, 1, mb_strlen($word), 'utf8');
return mb_strtoupper($firstChar) . $rest;
<?php
$string = 'Пусть этой строкой будет вот прямо эта строка';
$array = explode(' ', $string);
$string_result = '';
foreach ($array as $value) {
$fist_let = mb_strtoupper($value{0}.$value{1});
$string_result .= $fist_let . substr($value, 2). ' ';
}
echo $string_result;
function solution() {
let arr = Array.apply(null, {length: 100}).map(Number.call, Number);
return arr.filter(el => el % 2 !== 0)
.map((el, i, arr) => ((i + 1) % 2 !== 0) ? el + arr[i + 1] : 0)
.map(el => parseInt(el, 10).toString(2))
.filter(el => countChar(el, "1") === countChar(el, "0"))
.reduce((sum, cur) => sum + countChar(cur, "1"), 0);
function countChar(str, symbol) {
<?php
$start = microtime(true);
//1,2 алгоритм
$array = [];
while ($i <= 100) {
$i & 1 ? ($array[] = $i) : null;
$i++;
}
//разделяем массив на два по четности
// Задание:
// 1) генерируем последовательность натуральных чисел до ста
// 2) оставляем только нечетные
// 3) складываем их попарно
// 4) оставляем только те, у которых в бинарном представлении
// количество единиц и нулей одинаковое
// 5) возвращаем общее количество единиц
'use strict'
@straybro
straybro / Phpunit-assert_exception.php
Created May 12, 2020 21:50 — forked from VladaHejda/Phpunit-assert_exception.php
Phpunit Exception assertion. For easy multiple testing if Exception is thrown in one test method. For PHP >= 5.5 you can use package with trait: https://packagist.org/packages/vladahejda/phpunit-assert-exception
<?php
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
protected function assertException(callable $callback, $expectedException = 'Exception', $expectedCode = null, $expectedMessage = null)
{
$expectedException = ltrim((string) $expectedException, '\\');
if (!class_exists($expectedException) && !interface_exists($expectedException)) {
$this->fail(sprintf('An exception of type "%s" does not exist.', $expectedException));
}
@straybro
straybro / text.md
Created May 8, 2020 20:12 — forked from davydovanton/text.md
Рефакторинг сервис объекта с монадами и AR

https://t.me/pepegramming

Сегодня попался рельсовый код, в котором используются монады, сервисы и прочее. Решил сделать обзор с объяснением того, что в коде не нравится и что можно исправить.

Данный разбор основан только на личном опыте и избегает попытку написать самый идеальный код на свете. К сожалению пошарить ссылку на код не могу, потому что автор попросил опубликовать анонимно.

Исходные данные

Главная операция, которая вызывается из контроллера выглядит следующим образом:

@straybro
straybro / closurize.php
Created May 2, 2020 06:56 — forked from rintaun/closurize.php
closurize(): Converts any valid PHP callable into a Closure. Requires PHP 5.4.0+.
<?php
/**
* Converts any valid PHP callable into a Closure. Requires PHP 5.4.0+.
*
* The ramifications of this are many, but basically it means that any function
* or method can be converted into a Closure, bound to another scope, and
* executed easily. Works properly even with private methods.
*
* - On success, returns a Closure corresponding to the provided callable.
* - If the parameter is not callable, issues an E_USER_WARNING and returns a
@straybro
straybro / iteration-and-recursive-iteration.php
Created April 27, 2020 22:54 — forked from hakre/iteration-and-recursive-iteration.php
Iteration and Recursive Iteration Examples Code
<?php
/*
* Iteration and Recursive Iteration Examples Code
*
* @link http://stackoverflow.com/questions/12077177/how-does-recursiveiteratoriterator-works-in-php
* @author hakre <http://hakre.wordpress.com>
*/
### To have these examples to work, a directory with subdirectories is needed,
### I named mine "tree":