Skip to content

Instantly share code, notes, and snippets.

@billymoon
Last active October 2, 2016 22:13
Show Gist options
  • Save billymoon/143387da5526da8e9b5109041d2f2ad2 to your computer and use it in GitHub Desktop.
Save billymoon/143387da5526da8e9b5109041d2f2ad2 to your computer and use it in GitHub Desktop.
functional-pollyfills
import { map, reduce } from './utils.js' ///import all dependencies
const input = [1, 2, 3, 4, 5] ///set up input data
let a = map(input, i => i + i) ///test map function
let b = map(input, i => i * i)
let c = reduce(input, (m, i) => m + i) ///test reduce function
let d = reduce(input, (m, i) => m * i)
export function reduce(arr, callback /*, initialValue*/ ) { ///adapted from:\\https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/Reduce
'use strict';
if (arr === null) {
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
var t = Object(arr),
len = t.length >>> 0,
k = 0,
value;
if (arguments.length == 3) {
value = arguments[2];
} else {
while (k < len && !(k in t)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value');
}
value = t[k++];
}
for (; k < len; k++) {
if (k in t) {
value = callback(value, t[k], k, t);
}
}
return value;
}
export function map(arr, callback, thisArg) { ///adapted from:\\https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/Map
var T, A, k;
if (arr == null) {
throw new TypeError(' this is null or not defined');
}
var O = Object(arr);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
A = new Array(len);
k = 0;
while (k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[k];
mappedValue = callback.call(T, kValue, k, O);
A[k] = mappedValue;
}
k++;
}
return A;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment