File: implementation.js

package info (click to toggle)
node-string.prototype.codepointat 1.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 140 kB
  • sloc: javascript: 197; makefile: 2
file content (34 lines) | stat: -rw-r--r-- 1,186 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*! https://mths.be/codepointat v1.0.0 by @mathias */

'use strict';

var callBound = require('es-abstract/helpers/callBound');
var RequireObjectCoercible = require('es-abstract/2019/RequireObjectCoercible');
var ToString = require('es-abstract/2019/ToString');
var ToInteger = require('es-abstract/2019/ToInteger');
var StringCharCodeAt = callBound('String.prototype.charCodeAt');

module.exports = function codePointAt(position) {
	var O = RequireObjectCoercible(this);
	var string = ToString(O);
	var size = string.length;
	var index = ToInteger(position);
	// Account for out-of-bounds indices:
	if (index < 0 || index >= size) {
		return undefined;
	}
	// Get the first code unit
	var first = StringCharCodeAt(string, index);
	var second;
	if ( // check if it’s the start of a surrogate pair
		first >= 0xD800 && first <= 0xDBFF && // high surrogate
		size > index + 1 // there is a next code unit
	) {
		second = StringCharCodeAt(string, index + 1);
		if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
			// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
			return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
		}
	}
	return first;
};