PHP's end in TypeScript

Rosetta Stone: ruby/last

How to use

Install via yarn add locutus and import: import { end } from 'locutus/php/array/end'.

Or with CommonJS: const { end } = require('locutus/php/array/end')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1end({0: 'Kevin', 1: 'van', 2: 'Zonneveld'})'Zonneveld'
2end(['Kevin', 'van', 'Zonneveld'])'Zonneveld'

PHP arrays and TypeScript/JavaScript

Please note that Locutus uses TypeScript/JavaScript objects as substitutes for PHP arrays, they are the closest we can get to this hashtable-like data structure without rolling our own. While many TypeScript/JavaScript implementations preserve the order of object properties, the ECMAScript Language Specification explicitly states that:

The mechanics and order of enumerating the properties is not specified.

In practice most engines preserve insertion order, but if your code depends on key ordering across platforms, keep this caveat in mind.

To influence how Locutus treats objects as arrays, you can check out the locutus.objectsAsArrays setting.

Notes

  • Uses global: locutus to store the array pointer

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to PHP's end looks like.

import { getArrayLikeLength, getEntryAtCursor, getPointerState } from '../_helpers/_arrayPointers.ts'
import type { PhpArrayLike } from '../_helpers/_phpTypes.ts'

export function end<T>(arr: PhpArrayLike<T>): T | false {
// discuss at: https://locutus.io/php/end/
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Legaev Andrey
// revised by: J A R
// revised by: Brett Zamir (https://brett-zamir.me)
// improved by: Kevin van Zonneveld (https://kvz.io)
// improved by: Kevin van Zonneveld (https://kvz.io)
// note 1: Uses global: locutus to store the array pointer
// example 1: end({0: 'Kevin', 1: 'van', 2: 'Zonneveld'})
// returns 1: 'Zonneveld'
// example 2: end(['Kevin', 'van', 'Zonneveld'])
// returns 2: 'Zonneveld'

const state = getPointerState(arr, true)
if (!state) {
return false
}

const lastIndex = getArrayLikeLength(arr) - 1
if (lastIndex < 0) {
return false
}

const entry = getEntryAtCursor(arr, lastIndex)
if (!entry) {
return false
}

state.setCursor(lastIndex)
return entry[1]
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP array functions


Star