# Category Archives: CODING

## (Dart) Round integer to 10,100, 1000 etc.

If you need to shave off the last few digits of a big int, you can use this simple solution. Came in handy for me when working with milliseconds in timers. Basically you cast the integer to a double and divide it by the number of 0’s you want at the end. Then round, ceil or floor it and turn it back into an int.

For type safety you might have to do some more meticulous work, depending on the language you’re working in. Here’s an example in Dart.

```  var integerToRound = 31555;
var roundedInteger = (integerToRound / 10).floor() * 10;

print(roundedInteger);

//output: 31560
```

Change the divider and multiplier to the number of zeros you need.

```  var integerToRound = 31555;
var roundedInteger = (integerToRound / 100).floor() * 100;

print(roundedInteger);

//output: 31600
```

## (JS) Calculate price excluding VAT

Sometimes you need to calculate the price of a product excluding VAT, and the only details you have is the amount including vat and the vat percent. This might be a bit tricky in some applications when there are mixed VAT percentages.

For example, you payed 1000 space credits and in that sum there is a 12% VAT included. If you need to find out how much of the 1000 is actual VAT you can use this simple function:

```function getAmountWithoutVat(amountIncludingVat, vatPercent) {

var amountExVat = amountIncludingVat / (100 + vatPercent) * 100;
var sumVat = amountIncludingVat - amountExVat;
var amounts = {
'priceExVat' : amountExVat.toFixed(2),
'vat' : sumVat.toFixed(2)
};

return amounts;
}

console.log(getAmountWithoutVat(1000, 12));
```

Output:

```{
priceExVat: "892.86",
vat: "107.14"
}
```

## (JS) Validate date in format YYYY-MM-DD

A simple JS function to validate that a date string in the format YYYY-MM-DD is a valid date. Will validate that the day is correct for the given month, including leap years

```/**
* Validate that a date string in the format YYYY-MM-DD is a valid date
* @param dateString (YYYY-MM-DD)
* @returns {boolean}
*/
function isValidDate(dateString) {

// Date format: YYYY-MM-DD
var datePattern = /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;

// Check if the date string format is a match
var matchArray = dateString.match(datePattern);
if (matchArray == null) {
return false;
}

// Remove any non digit characters
var cleanDateString = dateString.replace(/\D/g, '');

// Parse integer values from date string
var year = parseInt(cleanDateString.substr(0, 4));
var month = parseInt(cleanDateString.substr(4, 2));
var day = parseInt(cleanDateString.substr(6, 2));

// Define number of days per month
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
daysInMonth[1] = 29;
}

// check month and day range
if (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1]) {
return false;
}

return true;
}
```

## (JS) Validate Swedish personnummer and organisationsnummer

Javascript functions for validating Swedish personal identity numbers (personnummer), and organisation numbers (organisationsnummer). The functions for personal identity number will also validate co-ordination number (samordningsnummer).

```  /**
* Validate a 10 digit swedish personnummer
* @param pnr
* @returns {boolean|boolean}
*/
function validatePersonnummer(pnr) {
var personummer = cleanDigitString(pnr);
if (personummer.length > 10) {
return false;
}

return isValidLuhn(personummer) && isPersonnummerDate(personummer);
}

function validateOrganisationNumber(orgnr) {
var orgnumber = cleanDigitString(orgnr);

if (orgnumber.length < 10 || orgnumber.length > 12 || orgnumber.length == 11) {
console.log(orgnumber.length);
}

return isValidLuhn(orgnumber);
}

/**
* Remove any non digit characters
* @param digitString
* @returns {*}
*/
function cleanDigitString(digitString) {
return digitString.replace(/\D/g, '');
}

/**
* Check if date is valid for personnummer
* @param pnr
* @returns {boolean}
*/
function isPersonnummerDate(pnr) {
var year = parseInt(pnr.substring(0, 2));
var month = parseInt(pnr.substring(2, 4));
var day = parseInt(pnr.substring(4, 6));

// Check year and month values
if (year < 0 || year > 99 || month < 0 || month > 12) {
return false;
}

var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
daysInMonth[1] = 29;
}

// Check that day is within range
var dayIsValid = day > 0 && day <= daysInMonth[month - 1];

// If day is outside range, check if it's +60 for samordningsnummer
if (!dayIsValid) {
dayIsValid = day > 60 && day <= daysInMonth[month - 1] + 60;
}

return dayIsValid;
}

/**
* Check if last digit of number is vald Luhn control digit
* @param pnr
* @returns {boolean}
*/
function isValidLuhn(pnr) {
var number;
var checksum = 0;
for (var i = pnr.length - 1; i >= 0; i--) {
number = parseInt(pnr.charAt(i));
if (i % 2 == 1) {
checksum += number;
} else {
checksum += (number * 2) > 9 ? (number * 2) - 9 : number * 2;
}
}

return checksum % 10 == 0;
}
```

## Laravel with SSL through Cloudflare on Heroku.

I deployed a Laravel app on Heroku, using Cloudflare for SSL. As a quick note, here’s how I did it.

1. Deploy the app on Heroku and make sure everything works fine using the heroku app url.
2. Add the domain names to your app in Heroku (in the settings tab for the app). Make sure you add both the root domain and www if you’re using it (example.com, www.example.com). Don’t activate SSL in Heroku.
4. Point your domain to Cloudflare by changing the name servers  (at the registrars control panel) to the ones Cloudflare gives you when adding the site.
5. Wait for the name server changes to go through. It will be notified under the Overview tab on Cloudflare. When this is done you will administer the domain records on Cloudflare instead of your domain regristrar.
6. Remove all the DNS records you don’t need, under the DNS tab in Cloudflare.  For the next step to work you need to remove the A records for the root domain – since you won’t point it to an IP address, but a domain on Heroku.
7. Point Cloudflare to your Heroku app by adding cname records pointing to the Heroku app url.
Like this.

Type: CNAME
Name: jymden.com
Domain name: myapp.herokuapp.com

Type: CNAME
Name: www
Domain name: myapp.herokuapp.com

8. In Cloudflare, go to the Crypto tab. Set SSL to Full:
9. Make sure your Universal SSL certificate is activated. This will happen automatically a little while after adding the site to Cloudflare (up to 24 hours, but usually faster).  When it’s activated you’ll see it a bit down in the Crypto tab, like this:
10. Prepare your Laravel app to use https by adding this to the boot function AppServiceProvider.php (App/Providers):
```public function boot(UrlGenerator \$url)
{
if (env('APP_ENV') !== 'local') {
\$url->forceSchema('https');
}
}
```

NOTE: if you’re using Laravel 5.4 or higher it’s forceScheme instead of forceSchema

Also, you need to set your Laravel environment variable APP_ENV to production (or at least something else than local). Do this in the Heroku app settings tab.

11. Now try to enter your site with https. It might take a while for it to kick in.
12. When you see that https is working correctly, go in to the Page Rules tab in Cloudflare. Click Create Page Rule and add the rule to always use https for the domain. Use wildcards to cover all urls. Like this:
13. Drink coffee.

## (JS) Use include method in IE

Here’s a hack for using the includes method also in the horrible Internet Explorer.

```if (!String.prototype.includes) {
String.prototype.includes = function () {
'use strict';
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
```

## (PHP) Serve Laravel to the web

This will make your Laravel instance available on the web. Make sure your router have port 80 forwarded to your machine. Also make sure no other server applications is blocking the port.

```php artisan serve --host 0.0.0.0 --port 80
```

## (PHP) Sort array of objects by property value

```usort(\$myArray, function(\$a, \$b)
{
return strcmp(\$a->myPropery, \$b->myPropery);
});
```

Sort by predefined order:

```\$predefinedOrder = array(1,5,2,6);

usort(\$arrayOfObjects, function (\$a, \$b) use (\$predefinedOrder ) {

\$flipped = array_flip(\$predefinedOrder);
\$left = \$flipped[\$a->myPropery)];
\$right = \$flipped[\$b->myPropery)];
return \$left >= \$right;
});
```

## (PHP) Add column to table in Laravel

Create migration in console:

```php artisan make:migration add_mycolumn_to_mytable
```

Use Schema::table() to access existing table (instead of Schema::create() for creating new tables)

```public function up()
{
Schema::table('mytable', function(\$table) {
\$table->text('mycolumn');
});
}
public function down()
{
Schema::table('mytable', function(\$table) {
\$table->dropColumn('mycolumn');
});
}
```

Then run migrations:

```php artisan migrate

```

## (PHP) Allow Composer to connect to http/https

If you have problems with Composer not allowing to update to http-connections add this to composer.json (not recommended to keep in production)

```config : {
"secure-http" : false
}
```